【问题标题】:Selenium xpath unable to locate classSelenium xpath 无法定位类
【发布时间】:2020-07-18 00:11:41
【问题描述】:

我正在做一个收集数据的项目。我有一个贯穿 50 个 url 的 for 循环(所有这些都是同一个页面,只是信息不同),然后我提取不同的东西添加到 csv 中。我遇到的问题是,当我尝试在我的代码中提取“job_title”时,许多条目都显示为“无”,尽管该条目实际上存在。每个 URL 中的 HTML 似乎都相同,但 10/50 的 URL 对以下代码行产生了“NONE”。我需要代码来设置 job_title = 'Founder'

这是我目前使用的代码:

sel = Selector(text=driver.page_source) 
job_title = sel.xpath('//*[starts-with(@class, "t-16 t-black t-bold")]/text()').extract_first()

这是来自我无法提取 job_title 的 URL 之一的 HTML——在这种情况下是“Founder”。这是脚本的第二行。

<div class="pv-entity__summary-info pv-entity__summary-info--background-section mb2">
  <h3 class="t-16 t-black t-bold">Founder</h3>
  <p class="visually-hidden">Company Name</p>
  <p class="pv-entity__secondary-title t-14 t-black t-normal">
    Genamint
    <span class="pv-entity__secondary-title separator">Full-time</span>
  </p>
  <div class="display-flex">
    <h4 class="pv-entity__date-range t-14 t-black--light t-normal">
      <span class="visually-hidden">Dates Employed</span>
      <span>Mar 2020 – Present</span>
    </h4>
    <h4 class="t-14 t-black--light t-normal">
      <span class="visually-hidden">Employment Duration</span>
      <span class="pv-entity__bullet-item-v2">5 mos</span>
    </h4>
  </div>

  <h4 class="pv-entity__location t-14 t-black--light t-normal block">
    <span class="visually-hidden">Location</span>
    <span>New York, United States</span>
  </h4>

  <!---->
</div>

任何帮助将不胜感激。

【问题讨论】:

  • 您是否在寻找命名空间问题?如果输入这个 XPath 会产生什么结果://*[local-name()='h3'][contains(@class,"t-16 t-black t-bold")]。空格问题?您能否测试以下表达式://h3[contains(@class,"t-16") and contains(@class,"t-black") and contains(@class,"t-bold")]
  • 这两行都抓取了这个 HTML。 ''

标签: python html selenium xpath


【解决方案1】:

这两行都抓取了这个 HTML。 &lt;h3 class="nav-settings__member-name t-16 t-black t-bold&gt; Ethan Roberti &lt;/h3&gt;

您的示例数据中没有nav-settings__member-name。由于您使用的是extract_first(),因此您会得到第一个出现的结果。解决它的一种方法是:

(//div[contains(@class,"pv-entity__summary")])[1]//h3/text()

输出:Founder

假设您正在尝试抓取 LinkedIn,以获取某人当前或上一份工作,请使用以下 XPath:

(//section[@class="experience pp-section" or @id="experience-section"]//h3)[1]/text()

例如,对于https://www.linkedin.com/in/ethan-roberti-322694174,您将获得:

输出:Summer Analyst

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多