【问题标题】:Not finding the Correct xpath找不到正确的 xpath
【发布时间】:2014-09-24 21:23:19
【问题描述】:

我正在尝试编写一个 Python 脚本来从屏幕右上角列出的 Google 产品中获取一些信息。 (一般6张图有价格和卖家)

我正在使用 Python、PhantomJS 和 Selenium

在谷歌搜索“红鞋”我希望我的脚本返回价格。我陷入了试图找到包含产品的元素的步骤。我的 xpath 是否遗漏了什么?

    def getTopSongs(object):
    print "Working YETI"
    browser = webdriver.PhantomJS('c:/projects/phantomjs/phantomjs.exe')
    browser.get('http://google.com/search?q=red+shoe')
    time.sleep(5)
    title = browser.find_element_by_xpath('//div[contains@class, "pla-unit")]/text()[contains(., "red")]/following::b').text

从谷歌的网页中我嵌套了几个元素

<div id="rhs">
...
 <div class="_Pwb">
  <div class="_Ohb">
   <div style="width:109px" class="pla-unit">
    <div class="_PD">
     <div class="pla-unit-img-container">
     <div class="_Z5">
       <div class="_vT"><a href="http://www.somewebsite.com">
         <span class="rhsl4">Nina 'Forbes' Peep Toe Pump <b>Red</b> R...</span>
         <span class="rhsg3 rhsl5">Nina 'Forbes' Peep Toe Pum...</span>
         <span class="rhsg4">Nina 'Forbes' Peep Toe Pu...</span></a>
       </div>
       <div class="_QD"><b>$78.95</b></div>
       <div class="_mC">
         <span class="rhsl4 a">Nordstrom</span>
         <span class="rhsg3 rhsl5 a">Nordstrom</span>
         <span class="rhsg4 a">Nordstrom</span>
       </div>
      </div>

*更新: 我添加了更多的 HTML。在此示例中,我希望从 ($78.95) 和 (Norstrom) 获取文本

*更新 澄清一下,

<div id="rhs">

是一个独特的元素

但是有多个 (6) 元素:

<div style="width:109px" class="pla-unit">

每个类别下的元素具有相同的名称并遵循相同的结构和子结构 即有6个

 <div class="_PD">
  <div class="pla-unit-img-container">
 <div class="_Z5">
  <div class="_vD">
  <div class="_QD">
  <div class="_mC">

等等。

主要目标是获取所有元素,但出于调试目的,我寻求帮助以获取第一个元素。

在 Firefox 上使用 XPathChecker 的价格单位的 xpath 是: id('rhs_block')/x:div[1]/x:div/x:div/x:div/x:div[1]/x:div[1]/x:div[2]/x:div [2]/x:b

【问题讨论】:

  • 你能显示更多的 HTML 吗? div[@class='pl-unit']? 之后到底是什么
  • 你的 XPath 不好。 text() 节点没有子节点。
  • @SiKing 路径表达式不查找文本节点的子节点。 following::child:: 之外的另一个轴。
  • 现在好多了,但还不清楚规则是什么。例如:span 的class 属性(例如span/@class='rhs14)是否唯一?您是否正在寻找div[@pla-unit] 之后的第一个span 元素,它的b 子元素又包含“红色”?价格总是在紧随其后的div 中吗?品牌名称是否始终位于 class 属性与包含“Red”的 span 相同,加上一个“a”(例如“rsh14 a”)?
  • 结构是一样的,我在找
    里面的文字文本

标签: selenium xpath xpath-2.0


【解决方案1】:

您可以使用祖先::返回,然后使用following-sibling::获取跟随它的同一级别的元素。

我没试过,但试一试:

title = browser.find_element_by_xpath('//div[contains@class, "pla-unit")]/text()[contains(., "red")]/ancestor::div/following-sibling::div[1]').text

然后到你的 div class='mC' 你只需改变:

following-sibling::div[1]

following-sibling::div[2]

并从其下的 span 中获取文本。

【讨论】:

  • 感谢 Brandon,它仍然无法正常工作。我收到“无法使用 xpath 表达式定位元素 //...
  • 我认为它只是找不到“pla-unit”,因此无法前进
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多