【问题标题】:selenium Unable to locate element by xpathselenium 无法通过 xpath 定位元素
【发布时间】:2020-06-28 07:31:37
【问题描述】:

我正在尝试将网站抓取到 csv 文件,但我无法找到一些文本元素。

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

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

我为site 中的其他元素工作的代码行(如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");''')

【问题讨论】:

  • 这听起来像X-Y problem。与其寻求解决问题的帮助,不如编辑您的问题并询问实际问题。你想做什么?
  • 我只需要 csv 表中的整个页面
  • 您看到的是NoSuchElementException,您如何在 csv 表中获取整个页面?请edit the question 将其限制为具有足够详细信息的特定问题,以确定适当的答案。避免一次问多个不同的问题。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • 我希望你现在更清楚了

标签: python selenium xpath selenium-chromedriver


【解决方案1】:

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

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

进口:

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")

【讨论】:

  • 谢谢,但不是这样,我在代码中等待了 10 秒,现在我实际上看到了页面加载。例如,如果您将输入此链接:link 在 H1(餐厅名称)下有类别名称,我可以随时获取餐厅名称,但我无法以任何方式获取类别名称。它让我发疯,我尝试了一堆 xpath,但它没有得到它//*[contains(@class,'VenueHeroBanner__description')]/p
【解决方案2】:

我不明白,但是如果你给他你想要得到的孩子的父 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"

【讨论】:

  • 太棒了!做得好。也许div 的子元素没有被评估为p 元素。如果你使用会发生什么://*[contains(@class,'descriptionContainer')]/*[1] 如有必要,增加位置索引 (1)。
猜你喜欢
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
相关资源
最近更新 更多