当前位置: 代码迷 >> python >> Python Selenium查找元素XPath不起作用
  详细解决方案

Python Selenium查找元素XPath不起作用

热度:26   发布时间:2023-07-16 10:21:14.0

我尝试在网页上找到推荐元素(时间)。 我的代码之前仅适用于简单文本。 现在,我使用Ctrl + Shift + I并指出我的元素和“复制Xpath”

另外,我有Chrome扩展程序“ XPath helper”,并尝试使用它之一。 XPath比下面的代码中的更长。 而且它也不起作用。

错误:NoSuchElementException:消息:没有这样的元素:无法找到元素:{“ method”:“ xpath”,“ selector”:“ // * [@ id ....

而且,我还尝试使用按类,按标签,按CSS选择器使用find。它仅按标签工作,而在不同页面上不完美。

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

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

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

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)

这将在您希望该页面的数据不包含任何特定元素的情况下起作用:

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)

假设你想spcipic数据,可以使用contains() Xpath的方法......你可以阅读这个

对于您的情况:

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的那一部分。

希望这对您有所帮助!

  相关解决方案