我對 Python/編碼很陌生,所以請和我一起裸露。
但是,我試圖通過抓取頁面的“webelement”并使用 Selenium 查找其值來從網頁標題(由用戶輸入)中提取文本。
但是,它一直只回傳值“無”,而不是我期望看到的值(在本例中為“黑色束帶裹身大衣”。
代碼可以在下面找到:
title = driver.find_elements(By.XPATH,('/html/body/div[4]/div/div[3]/div[4]/div[1]/div[1]/form/div/div[2]/a/h2'))
//其余代碼隱藏,但如果您需要更多,請告訴我。(我是新手,不想發垃圾郵件)
知道是什么原因造成的嗎?
我輸入的源網址是:https : //www.riverisland.com/p/black-belted-wrap-coat-782866
這運行沒有錯誤,但回傳一個意外的值(如下圖所示)。
在此 輸入圖片說明 在此輸入圖片說明
如果我錯過了任何東西,請欣賞它并道歉。姜
uj5u.com熱心網友回復:
如果你正在努力尋找一個元素的使用find_element,而不是find_elements。find_elements將回傳一個 webelement 串列。
嘗試使用以下代碼:
Imports required for Explicit waits
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get("https://www.riverisland.com/p/black-belted-wrap-coat-782866")
wait = WebDriverWait(driver,30)
# Click on Accept cookies
wait.until(EC.element_to_be_clickable((By.NAME,"accept-all"))).click()
title = wait.until(EC.visibility_of_element_located((By.XPATH,"//h2[@data-localize='Product_Title']")))
print(title.text)
BLACK BELTED WRAP COAT
uj5u.com熱心網友回復:
要列印文本,BLACK BELTED WRAP COAT您可以使用以下任一定位器策略:
使用
css_selector和get_attribute("innerHTML"):print(driver.find_element(By.CSS_SELECTOR, "h2.product-title.ui-product-title").get_attribute("innerHTML"))使用
xpath和文本屬性:print(driver.find_element(By.XPATH, "//h2[@class='product-title ui-product-title']").text)
理想情況下,你需要引起WebDriverWait的visibility_of_element_located(),你可以使用以下的定位策略:
使用
CSS_SELECTOR和文本屬性:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[name='accept-all']"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2.product-title.ui-product-title"))).text)使用
XPATH和get_attribute("innerHTML"):WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@name='accept-all']"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[@class='product-title ui-product-title']"))).get_attribute("innerHTML"))
控制臺輸出:
BLACK BELTED WRAP COAT
注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在如何使用 Selenium 檢索 WebElement 的文本 - Python 中找到相關討論
參考
鏈接到有用的檔案:
get_attribute()方法Gets the given attribute or property of the element.text屬性回傳The text of the element.- 使用 Selenium 的 text 和 innerHTML 之間的區別
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355802.html
