簡體   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