硒无法通过xpath定位元素

时间:2020-06-28 07:31:37

标签: python selenium xpath selenium-chromedriver

我正在尝试将网站抓取到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");''')

2 个答案:

答案 0 :(得分:0)

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

Pizzas

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

进口:

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

答案 1 :(得分:0)

我不理解方法,但是如果您给他想要获得的孩子的父级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"