如何在selenium中通过XPath查找具有多个类的元素?

2024-07-01 07:01:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从Upwork job search中刮取所有工作的标题,这些标题存储在如下标记中:

<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')]")

但这两种方法都只返回空列表——这很奇怪,因为这表明它正在匹配某些内容?因为如果它不能匹配一个元素,我会预料到一个错误

有谁能为如何实现这一目标提供建议吗

谢谢


Tags: and标题datatitleemailcustomjobsjob
3条回答

看看这是否有帮助:-

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

首先,您正试图匹配只有一个类名job-title的元素,而那里有更多的类名,因此您应该在那里使用contains。像这样:

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

您可能还必须在加载页面之前添加等待/延迟。
但首先你必须使用正确的定位器

使用以下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)

相关问题 更多 >

    热门问题