【问题标题】:How do I find elements by XPath in selenium with multiple classes?如何通过 XPath 在 selenium 中查找具有多个类的元素?
【发布时间】:2021-06-10 13:27:17
【问题描述】:

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

但是这两种方法都只返回空列表 - 这很奇怪,因为这表明它正在匹配某些东西?因为如果它不能匹配一个元素,我会期待一个错误。

谁能建议如何实现这一目标?

谢谢!

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping xpath


    【解决方案1】:

    首先,您尝试匹配具有恰好 1 个类名 job-title 的元素,而那里有更多类名,因此您应该在那里使用 contains。像这样:

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

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

    【讨论】:

      【解决方案2】:

      看看这是否有帮助:-

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-12
          • 1970-01-01
          • 2015-11-10
          • 2021-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-22
          相关资源
          最近更新 更多