【问题标题】:How do I scrape nested data using selenium and Python如何使用 selenium 和 Python 抓取嵌套数据
【发布时间】:2017-09-09 02:37:34
【问题描述】:

我基本上想在<h3 class="Sans-17px-black-85%-semibold"> 下刮Litigation Paralegal 和在<span class="pv-entity__secondary-title Sans-15px-black-55%"> 下刮Olswang,但我看不到它。这是代码中的 HTML:

<div class="pv-entity__summary-info">

<h3 class="Sans-17px-black-85%-semibold">Litigation Paralegal</h3>

<h4>
  <span class="visually-hidden">Company Name</span>
  <span class="pv-entity__secondary-title Sans-15px-black-55%">Olswang</span>
</h4>


  <div class="pv-entity__position-info detail-facet m0"><h4 class="pv-entity__date-range Sans-15px-black-55%">
      <span class="visually-hidden">Dates Employed</span>
      <span>Feb 2016 – Present</span>
    </h4><h4 class="pv-entity__duration de Sans-15px-black-55% ml0">
        <span class="visually-hidden">Employment Duration</span>
        <span class="pv-entity__bullet-item">1 yr 2 mos</span>
      </h4><h4 class="pv-entity__location detail-facet Sans-15px-black-55% inline-block">
      <span class="visually-hidden">Location</span>
      <span class="pv-entity__bullet-item">London, United Kingdom</span>
    </h4></div>

</div>

这是我目前在代码中使用 selenium 所做的事情:

if tree.xpath('//*[@class="pv-entity__summary-info"]'):

   experience_title =  tree.xpath('//*[@class="Sans-17px-black-85%-semibold"]/h3/text()')
   print(experience_title)

   experience_company = tree.xpath('//*[@class="pv-position-entity__secondary-title pv-entity__secondary-title Sans-15px-black-55%"]text()')
   print(experience_company)

我的输出: 体验标题:[] []

【问题讨论】:

    标签: python-2.7 selenium xpath


    【解决方案1】:

    您的XPath 表达式不正确:

    • //*[@class="Sans-17px-black-85%-semibold"]/h3/text() 表示h3 的文本内容,即类名属性为"Sans-17px-black-85%-semibold" 的元素的child。相反,您需要

      //h3[@class="Sans-17px-black-85%-semibold"]/text()

      表示h3元素的文本内容,类名属性"Sans-17px-black-85%-semibold"

    • //*[@class="pv-position-entity__secondary-title pv-entity__secondary-title Sans-15px-black-55%"]text() 中,您忘记了text() 之前的斜线(您需要/text(),而不仅仅是text())。而且目标span 没有类名pv-position-entity__secondary-title。你需要使用

      //span[@class="pv-entity__secondary-title Sans-15px-black-55%"]/text()

    【讨论】:

      【解决方案2】:

      您可以使用 CSS 选择器轻松获得这两者,我发现它们比 XPath 更容易阅读和理解。

      driver.find_element_by_css_selector("div.pv-entity__summary-info > h3").text
      driver.find_element_by_css_selector("div.pv-entity__summary-info span.pv-entity__secondary-title").text
      

      . 表示类名 &gt; 表示子级(仅限下一级) 表示后代(以下任何级别)

      以下是一些帮助您入门的参考资料。

      CSS Selectors Reference

      CSS Selectors Tips

      Advanced CSS Selectors

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 2020-11-28
        • 2015-08-12
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        相关资源
        最近更新 更多