首页 > 解决方案 > 通过多个类的 HREF 属性在页面上查找元素

问题描述

我正在使用 Selenium 库和 python。在页面上我收到了多个报价,每个报价都有相同的链接开头https://www.example.com/offer/ .... 和相同的类,但问题是我找不到具有多个类的元素. 它还具有相同的属性“data-cy”

我试过了

offerName = driver.find_element_by_xpath("//a[contains(@class, 'marginright5') and contains(@class, 'link') and contains(@class, 'linkWithHash') and contains('detailsLink')]")

但由于这个错误它没有工作

selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "//a[contains(@class, 'marginright5') and contains(@class, 'link') and contains(@class, 'linkWithHash') and contains('detailsLink')]" is invalid: [Exception... "<no message>"  nsresult: "0x8060000d (<unknown>)"  location: "JS frame :: chrome://marionette/content/element.js :: element.findByXPath :: line 387"  data: no]

我怎样才能找到它们?

标签: pythonselenium

解决方案


好吧,就像错误消息说您的 xpath 无效一样,我可以在最后一个“包含”中看到一个错误。

尝试改变这个:

driver.find_element_by_xpath("//a[contains(@class, 'marginright5') and contains(@class, 'link') and contains(@class, 'linkWithHash') and contains('detailsLink')]"

对此:

driver.find_element_by_xpath("//a[contains(@class, 'marginright5') and contains(@class, 'link') and contains(@class, 'linkWithHash') and contains(@class, 'detailsLink')]"

推荐阅读