【问题标题】:Is there any way to get the xpath of a selenium web element?有什么方法可以获取 selenium web 元素的 xpath 吗?
【发布时间】:2021-03-15 09:54:20
【问题描述】:

我有一个充满关键字的数据库,我必须获取包含这些词的 Web 元素的 xpath。 (每个单词旁边都有一个可展开的列表按钮。点击我需要获取关键字的xpath并修改它以获得按钮XPath)。

我可以使用 selenium web 元素,

keyword_element = driver.find_element_by_xpath(f"//*[contains(text(), '{keyword}')]")

这只会获取包含这样关键字的元素的 selenium web 元素,

<selenium.webdriver.remote.webelement.WebElement (session="1df8dbbae8c93fd772a5134ed0666a7a", element="b3d2bc8d-0c8c-4fb0-b3d1-2a5d49537567")>

HTML dev 元素看起来像这样。

<span class="fancytree-node actlitetreeitem fancytree-exp-n fancytree-ico-c">
    <span class="fancytree-expander"></span>
    <span class="fancytree-checkbox"></span>
    <span class="fancytree-title">SNAPCHAT</span>
</span>

'SNAPCHAT' 是关键字,我需要访问'fancytree-checkbox' 元素。但我必须使用关键字 SNAPCHAT 来获取它。

有没有办法从中获取 web 元素的 xpath?

【问题讨论】:

  • 请同时发布关键字元素的相关 HTML 以及带有父节点的按钮元素?
  • @KunduK 现在已编辑

标签: python selenium selenium-webdriver web-scraping xpath


【解决方案1】:

使用任一xpath 来标识元素fancytree-checkbox

使用preceding-sibling

keyword_element = driver.find_element_by_xpath(f"//*[contains(text(), '{keyword}')]/preceding-sibling::span[1]")

OR 识别 parent 节点,然后识别它的 child

 keyword_element = driver.find_element_by_xpath(f"//span[.//*[contains(text(), '{keyword}')]]//span[@class='fancytree-checkbox']")

【讨论】:

  • 非常感谢。我还找到了一种通过使用 keyword_element 元素向后引导来访问该元素的方法。但你的方法效果更好。
猜你喜欢
  • 2021-01-13
  • 2010-11-27
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多