我正在撰寫一個簡單的 python/selenium 代碼來從 url 中提取資料。我想知道等待一組元素可見的最佳方法是什么,如下所示:
Element A: A dialog that randomly appears on the website. If the element is there, it must be closed/clicked. If not, ignored.
Element B: Article price. If the article is not free, the element is present on the website.
Element C: Article price. If the is free, the element is present on the website
Element D: Shipping time (sometimes it is inside an iframe)
Element E: Shipping time (other time is is outside the iframe)
有時,元素需要一段時間才能加載,所以我添加了一個 time.sleep(1.5)。我知道 selenium 有一個 expected_conditions 等待,但這適用于始終存在的元素。
這是我到目前為止的代碼,但我認為它不夠好,因為它使用了隱式等待。如何改進此代碼?
try:
time.sleep(1.5)
try:
#ElementA
driver.find_element(By.CSS_SELECTOR, "div.andes-dialog__wrapper div.andes-dialog__container a.andes-dialog_-close").click()
except: pass
try:
#Element B: Article price in iframe (not free)
shipping_price=driver.find_element(By.CSS_SELECTOR, "div.ui-shipping_column.ui-shipping_price span.price_amount").text
except:
#Element C: Article price in iframe (free)
shipping_price=driver.find_element(By.CSS_SELECTOR, "div.ui-shipping__column.ui-shipping_price").text
#Element D: Shipping time in iframe
shipping_time=driver.find_element(By.CSS_SELECTOR, "div.ui-shipping_column.ui-shipping_description span.ui-shipping__title").text
except Exception as e:
#Element E: Shipping time outside iframe
shipping_time=driver.find_element(By.CSS_SELECTOR, "form.ui-pdp-buybox div.ui-pdp-shipping p.ui-pdp-media__title").text
uj5u.com熱心網友回復:
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(6)
uj5u.com熱心網友回復:
你應該像這樣使用 WebDriverWait:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome("D:/chromedriver/94/chromedriver.exe")
driver.get("https://www.website.com")
# wait 60 seconds
wait = WebDriverWait(driver,60)
try:
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.ui-shipping_column.ui-shipping_price span.price_amount")))
shipping_price=driver.find_element(By.CSS_SELECTOR, "div.ui-shipping_column.ui-shipping_price span.price_amount").text
except Exception as ex:
# do something
print(ex)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/318583.html
上一篇:無法通過xpath單擊此按鈕
下一篇:如何找到以下HTML的元素?
