繁体   English   中英

selenium 无法通过 xpath 定位元素

[英]selenium Unable to locate element by xpath

我正在尝试将 web 站点刮到 csv 文件中,并且有一些我无法找到的文本元素。

我不断收到Message: no such element: Unable to locate element:

我正在尝试使用 xpath 获取元素,并且在开始寻找它们之前等待站点加载。

我适用于站点中其他元素(如 H1 标题)的代码行是: driver.find_element_by_xpath("//*[contains(@class,'descriptionContainer')]/p[1]").text

我尝试了几个 xpath 以确保:

//*[contains(@class,'VenueHeroBanner__description')]/p
//*div[contains(@class,'VenueHeroBanner__description')]/p
//*[contains(@class,'descriptionContainer')]/p[1]
//*[@id='venueHeroBanner']/div[2]/div[1]/p

** 并且所有这些都在名为“xpath helper”的 chrome 扩展中工作,但不在我的脚本中

请注意,我在新选项卡中打开链接,然后尝试获取元素(如果它很重要)

driver.execute_script(f'''window.open("{rest_links[0]}","_blank");''')

该网站似乎需要一些时间来加载数据。

比萨饼

您应该在脚本中添加预期条件。

进口:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

然后使用:

WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "your_XPath"))).text
...

旁注:您应该修复您的最后一个 XPath(返回 2 个元素)。

WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "(//a[contains(@class,'venueInfoLink')])[1]"))).get_attribute("href")

我不明白,但是如果你给他你想要得到的孩子的父母 xpath,xpath 就可以工作

<div class="VenueHeroBanner__descriptionContainer___3Q-jT">
    <p class="VenueHeroBanner__description___1wQwD xh-highlight">Bar & Restaurant</p>

不工作-

driver.find_element_by_xpath("//*[contains(@class,'descriptionContainer')]/p[1]").text

那一项工作:

driver.find_element_by_xpath("//*[contains(@class,'descriptionContainer')]").text
[output] "Bar & Restaurant"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM