簡體   English   中英

如何在 selenium 中找到具有多個類的 XPath 元素?

[英]How do I find elements by XPath in selenium with multiple classes?

我想從 Upwork 工作搜索中抓取所有工作的標題,這些標題存儲在這樣的標簽中:

<h4 data-job-title="::$ctrl.job" class="job-title m-xs-top-bottom p-sm-right ng-isolate-scope">
<a data-ng-bindhtml="jsuJobTitleController.job.title|truncateHtmlByWords:jsuJobTitleController.getWordsThreshold()" data-ng-click="jsuJobTitleController.onJobTitleClick($event)" data-ng-href="/jobs/Email-Analytics-Custom_~0150c1eb58019b8306/" class="job-title-link break visited ng-binding" data-ng-class="{'text-muted': jsuJobTitleController.isHidden}" data-itemprop="url" href="/jobs/Email-Analytics-Custom_~0150c1eb58019b8306/">
Email Analytics Custom
</a> 
</h4>

我嘗試過使用其中一種可能的類:

jobs = driver.find_elements_by_xpath('//h4[@class="job-title"]')

和所有的課程:

jobs = driver.find_elements_by_xpath("//h4[contains(@class, 'job-title') and contains(@class, 'm-xs-top-bottom') and contains(@class, 'p-sm-right') and contains(@class, 'ng-isolate-scope')]")

但是這兩種方法都只返回空列表 - 這很奇怪,因為這表明它正在匹配某些東西? 因為如果它不能匹配一個元素,我會期待一個錯誤。

誰能建議如何實現這一目標?

謝謝!

首先,您嘗試匹配恰好具有 1 個 class 名稱job-title元素,而那里有更多 class 名稱,因此您應該在那里使用contains 像這樣:

jobs = driver.find_elements_by_xpath('//h4[contains(@class,"job-title")]')

也可能您必須在此之前添加等待/延遲才能加載頁面。
但首先你必須使用正確的定位器

看看這是否有幫助:-

jobTitles = driver.find_elements_by_xpath(".//h4[contains(@class,'job-title')]/a")
for e in jobTitles:
    e.text

使用下面的 xpath:

//a[contains(@href, '/jobs/Email-Analytics-Custom')]

我建議有明確的等待

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href, '/jobs/Email-Analytics-Custom')]")))
element.click()

如果您想刮掉所有標題:

然后使用下面的 xpath:

//h4[@data-job-title]

使用find_elements將所有elements存儲在列表中

for title in driver.find_elements(By.XPATH, "//h4[@data-job-title]")
    print(title.text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM