我剛開始學習python。所以在本章中,它基本上是使用 selenium 創建一個價格跟蹤器。
下面的照片是我試圖使用硒獲得的。
截屏
如果我嘗試
search_box = driver.find_element(By.CLASS_NAME, "a-price a-text-price a-size-medium apexPriceToPay")
它顯示了紅色的線條海洋,沒有說任何訊息:沒有這樣的元素
然后我嘗試
search_box = driver.find_element(By.CLASS_NAME, "a-offscreen")
輸出為: <selenium.webdriver.remote.webelement.WebElement (session="0e1349ab77fff9cc0f9c565cc173927d", element="bbd837af-3cdf-4bd1-825c-9fd8cd27f719")>
我對編程真的很陌生……所以我最后嘗試使用 .text ,但不走運!
我該怎么做才能得到價格?
uj5u.com熱心網友回復:
我會試試這個:
search_box = driver.find_element(By.CLASS_NAME, "apexPriceToPay")
或許
search_box = driver.find_element(By.CSS_SELECTOR, ".a-price.a-text-price")
為了給出準確的答案,我們需要查看整個頁面的 HTML 以找到最短的唯一定位符
uj5u.com熱心網友回復:
您需要注意以下幾點:
您不能在其中傳遞多個類名,
driver.find_element(By.CLASS_NAME, "classA classB classC classD")因為它可能會引發無效選擇器。傳遞類名
a-offscreen選擇了18個元素,所以你甚至不能使用它。您將看到輸出為:
<selenium.webdriver.remote.webelement.WebElement (session="0e1349ab77fff9cc0f9c565cc173927d", element="bbd837af-3cdf-4bd1-825c-9fd8cd27f719")>當您列印元素本身時,您也不需要它。
解決方案
要列印文本,$20.97您可以使用以下定位器策略:
使用xpath和text屬性:
print(driver.find_element(By.XPATH, "//td[starts-with(., 'Price')]//following-sibling::td[1]/span[contains(@class, 'a-price')]/span[@aria-hidden='true']").text)
理想情況下,您需要為visibility_of_element_located()引入WebDriverWait,您可以使用以下定位器策略:
使用xpath,第二個
<span>和get_attribute("innerHTML"):print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[starts-with(., 'Price')]//following-sibling::td[1]/span[contains(@class, 'a-price')]/span[@aria-hidden='true']"))).get_attribute("innerHTML"))控制臺輸出:
$20.97注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在How toret the text of a WebElement using Selenium - 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/shujuku/381178.html
