簡體   English   中英

Selenium 找不到元素 | Python

[英]Selenium can't find element | Python

所以我想閱讀網站上的文字(提取數據)。 但是當我試圖找到元素時,python 會打印出一條錯誤消息(沒有這樣的元素異常......)。 該元素沒有唯一的 id 等,所以我使用“XPATH”,它不起作用。 在這種情況下,我想獲取帶有文本(或數據)“11 1. Jahrgangsstufe”的元素。 在此處輸入圖像描述 當我右鍵單擊並復制“XPATH”時,我復制了這個:“/html/body/center 2 /p[11/table/tbody/tr[61]/td”。但正如所說,這不能作為 XPATH 工作。 有人有任何線索嗎? 是否有元素 selenium 無法訪問? 到目前為止我的代碼: 在此處輸入圖像描述

代碼為文本:

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from secrets import  url
path = 'C:\Program Files (x86)\chromedriver.exe'

# opening chrome and website
driver = webdriver.Chrome(path)
driver.get(url)
sleep(0.1)

# clicking on right timetable
timetable = driver.find_element(By.CLASS_NAME, 'timetable-wrapper')
timetable.click()
sleep(0.1)

# opening the page on a clearer view (hardly to explain),
# but I did this because the "XPath helper"
# Chrome extension tool worked better here.
# also opens a new tab (if this is relevant)
other_page = driver.find_element(By.XPATH,"/html[@class=' js flexbox flexboxlegacy canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers no-applicationcache svg inlinesvg smil svgclippaths']/body[@class='noTouch noScroll']/div[@id='overlay']/div[@class='overlay-element']/div[@class='overlay-head']/div[@class='zoom-controls']")
other_page.click()
sleep(0.5)
# Here I want to get the right box, that has the XPAHT :
# /html/body/center[1]/p[1]/table/tbody/tr[61]/td
# But it cant be found. When I try to print out the page source, not the #complete page source is printed out too.

根據您的解釋,我相信您需要等待該元素加載。 首先,確保您有以下導入:

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

之后,嘗試像這樣定位元素:

trouble_element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "--your-actual-xpath--")))
print(trouble_element.get_attribute('outerHTML')

它應該打印出實際元素的 HTML,如果您使用的 XPATH 是正確的。

Selenium 文檔相當廣泛: https://www.selenium.dev/documentation/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM