【问题标题】:Python/Selenium xpath - Find parent / sibling elementPython/Selenium xpath - 查找父/兄弟元素
【发布时间】:2018-01-30 03:33:12
【问题描述】:

我有以下代码:带有“keep-product-list-cache”类的标签 a 和带有“promotion-tag gray”类的标签 div 在标签 div 下,带有 class=“product-wrapping”。

我想从标签 div 下具有类“promotion-tag gray”的 span class="content tc" 的相对位置获取标签 a 下的类“image”中的数据代码 (1017534)。

<div class="product-wrapping">
    <a class="keep-product-list-cache" href="/product/peach-gum-black-sugar-longan-tea-1017534-c2843">
        <div class="image">
            <img src="https://tore.com/images/tore/production/product/160px/1017534_1.jpg?1511440192" data-code="1017534" alt="tea">
                    </div>
    </a>
    <div class="promotion-tag grey">
        <span class="edge"></span>
        <span class="content tc">Sold Out</span>
        <span class="triangle"></span>
    </div>

我尝试了以下方法按父/兄弟位置定位,但它不起作用:

id = driver.find_elements_by_xpath('div[@class="promotion-tag grey"]//span[@class="content tc"]/..//preceding-sibling::a//div[@class="image"]//img')

获取属性:id[i].get_attribute("data-code")

但返回列表“id”的长度为 0。知道吗?提前致谢!

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    哦。唯一的错误是您忘记了表达式开头的//。

    id = driver.find_elements_by_xpath('//div[@class="promotion-tag grey"]//span[@class="content tc"]/..//preceding-sibling::a//div[@class="image"]//img')
    

    【讨论】:

      【解决方案2】:

      根据 HTML 从标签 div 下 span class="content tc" 的相对位置获取 &lt;a&gt; 标签下的类 image 中的数据代码 (1017534)对于 promotion-tag gray 类,您可以使用以下代码行:

      print(driver.find_element_by_xpath("//div[@class='promotion-tag grey']//span[@class='content tc']//preceding::a[@class='keep-product-list-cache']/div[@class='image']/img[contains(@src,'https://tore.com/images/tore/production/product')]").get_attribute("data-code"))
      

      【讨论】:

      • img 节点不能有任何子节点,所以get_attribute("innerHTML") 应用于img 将始终返回None
      • @Andersson 感谢您的指出。那是我的错,现在更正。
      • @DebanjanB 我在这个解决方案中仍然没有得到任何结果。不过,我从 Buaban 的回复中得到了正确的输出。感谢您的帮助。
      • 答案中调用的方法不同-也许这就是区别;-?添加 s 可能会有很长的路要走
      • @Dilettant 谢谢。根据问题,我看不到使用 find_elements 的任何要求,因为 OP 需要一个明确的 value 即 1017534 ,好像可以识别适当的 Locator Strategy find_element 会顺利运行。
      猜你喜欢
      • 2020-11-15
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多