【问题标题】:Python Selenium find element XPath doesn't workPython Selenium 查找元素 XPath 不起作用
【发布时间】:2018-10-04 16:41:28
【问题描述】:

我尝试在网页上找到重新定义的元素(时间分钟)。我的代码之前只适用于简单的文本。现在我使用 Ctrl+Shift+I 并指出我的元素和 "Copy Xpath"

另外,我有 Chrome 扩展程序 "XPath helper" 并尝试用它来做这件事。 XPath 比我下面的代码更长。而且也不行。

错误:NoSuchElementException:消息:没有这样的元素:无法定位元素:{"method":"xpath","selector":"//*[@id....

而且,我还尝试使用按类、按标签、按 CSS 选择器查找。它只在不同页面上按标签工作,没有完美。

我什至不说打印它,有时find_element(By.XPATH,'//*[...).text 工作,有时不。

我不明白,为什么它在一页上而不是在第二页上工作。我想稍后在 Flash 中使用 XPath 查找元素。

更新现在我重试代码,它工作了!但是在下一个网页上仍然不起作用..为什么它如此多变? XPath 更改,页面重新加载时还是什么?从 Flash 中获取文本(刷新)信息的最简单方法是什么,在 chrome 浏览器中打开?

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(r"C:\Users\vishniakov\Desktop\python bj\driver\chromedriver.exe",chrome_options=options)
driver.get("https://www.betfair.com/sport/football/event?eventId=28935432")
print(driver.title)
elem =driver.find_element(By.XPATH,'//*[@id="yui_3_5_0_1_1538670363144_2571"]').text
print(elem)

【问题讨论】:

  • 页面未立即完全加载:尝试在查找元素前几秒钟输入sleep:如果可行,您可能会开始考虑更好的解决方法
  • 动态元素(未立即加载)、隐藏元素、更改的元素都是您在浏览器调试器或扩展程序中“看到”的内容可能通过 selenium 失败的原因。您可能需要睡觉,或使用 ActionChain 使项目可见。
  • 你想要的元素文本作为id是动态生成的,所以你不会得到结果

标签: python selenium


【解决方案1】:

这将适用于假设您想要该页面的数据而不是任何特定元素

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.betfair.com/sport/football/event?eventId=28935730")
print(driver.title)
elem =driver.find_element(By.CSS_SELECTOR,'.scroller.context-event').text
print(elem)

【讨论】:

    【解决方案2】:

    假设您确实需要特定数据,您可以使用contains() Xpath 方法...您可以阅读此here

    对于您的情况:

    import selenium
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    driver = webdriver.Chrome(r"C:\Users\vishniakov\Desktop\python bj\driver\chromedriver.exe",chrome_options=options)
    driver.get("https://www.betfair.com/sport/football/event?eventId=28935432")
    print(driver.title)
    elements =driver.find_elements(By.XPATH,'//*[contains(@id, "yui_3_5_0_1_")]')
    print([i.text for i in elements])
    

    如果我的示例不起作用,您可以使用contains()...您必须找出id 的哪一部分发生了变化并排除ID 的那一部分。

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 1970-01-01
      • 2016-04-26
      • 2018-12-06
      • 2021-09-20
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多