【问题标题】:How to get XPath from the specific text in Python Selenium [duplicate]如何从 Python Selenium 中的特定文本中获取 XPath [重复]
【发布时间】:2020-12-22 18:17:36
【问题描述】:

下面的第一个xpath在大多数情况下可以找到我想要的,但在某些情况下xpath略有不同,这使得解决问题变得更加困难。

大多数情况下是第一个 xpath -->

driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/ul/div/li[3]/ul/li[4]/div/a').click()

在某些情况下是第二个 xpath-->

driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/ul/div/li[5]/ul/li[4]/div/a').click()

所以我正在寻找另一种通过特定文本查找 xpath 的方法。

另一种方式-->

driver.get(url)
html_source = driver.page_source
 if "the specific text" in html_source:
   <<find xpath where the specific text is>>

&lt;div ext:tree-node-id="7" class="x-tree-node-el x-tree-node-leaf x-unselectable text" unselectable="on"&gt;&lt;span class="x-tree-node-indent"&gt;&lt;img alt="" src="/js/extjs/resources/images/default/s.gif" class="x-tree-elbow-line"&gt;&lt;/span&gt;&lt;img alt="" src="/js/extjs/resources/images/default/s.gif" class="x-tree-ec-icon x-tree-elbow"&gt;&lt;img alt="" src="/js/extjs/resources/images/default/s.gif" class="x-tree-node-icon" unselectable="on"&gt;&lt;a hidefocus="on" class="x-tree-node-anchor" href="#" tabindex="1"&gt;&lt;span unselectable="on"&gt;the specific text&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;

有可能还是有其他方法?

【问题讨论】:

  • 你的xpath和html不同步,分享一下相关的html。而且看起来很笼统,请具体。请阅读minimal reproducible example 并相应地编辑您的帖子,并在以后的所有帖子中遵循相同的内容

标签: python selenium


【解决方案1】:

方案一:直接使用classname获取文本或按

driver.find_element_by_class_name("my-class").click()
driver.find_element_by_class_name("my-class").text

选项2:不要以/html/body/bla/bla/bla开头,您可以调用具有特定类名的锚标记并获取文本或按

press_me = driver.find_element_by_xpath("//a[@class='my-class']").click()
get_me_text = driver.find_element_by_xpath("//a[@class='my-class']").text

我希望它清楚:)

【讨论】:

  • 谢谢,但它被树节点包围,没有唯一的名称。我可以从这个 div ext:tree-node-id="7" 获取 xpath 吗?我认为这是找到 xpath 的唯一一种方法。
  • driver.find_element_by_xpath("//div[@class='x-tree-node-el' @ext:tree-node-id='7']/a").text
  • 我找到了答案。谢谢。 @Salman Waheed
  • driver.find_element_by_xpath("//span[text()='具体文本']").click()
猜你喜欢
  • 2019-03-08
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 2017-04-09
  • 2019-04-27
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多