如果手動進入除錯,則以下代碼將按預期運行,而如果只是運行則行為不端。
除了到達搜索頁面的一些初始代碼之外,我還請求一個我知道不存在的值(“ZQZZQ”),因此代碼應該分支到最后一個 else 陳述句。
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
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(
"/Users/bob/Documents/work/AIFA/scraper/scrape_gu/chromedriver"
)
# navigate through the initial agreement screens
driver.get("https://farmaci.agenziafarmaco.gov.it/bancadatifarmaci/cerca-farmaco")
readunderstood = driver.find_element_by_id("conf")
readunderstood.click()
accept = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[5]/div[3]/div/button"))
)
accept.click()
# end of the initial agreement screens and general preparation
##############################################################
string_to_search = "ZQZZQ" # we can safely assume this does not exist
find_textbox = driver.find_element_by_id("search")
find_textbox.clear() # after the first search the old value will still be there
find_textbox.send_keys(string_to_search)
find_textbox.send_keys(Keys.ENTER)
# check if any results found
element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.ID, "noresultsfound"))
)
# if we did retrieve something we don't have an error message
if element.text != "Nessun risultato trovato":
# first we have to find out the total number of retrieved pages
print(f"Digram {string_to_search} found!")
else:
print(f"Digram {string_to_search} not found. Need to close modal window!")
# click on ok of name not found modal dialog
WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[4]/div[3]/div/button"))
).click()
print("Modal window hopefully closed")
當我全速運行它時,我發現它進入了“if”分支,列印“Digram ZQZZQ found!” 這是錯誤的。
WebDriverWait 呼叫是否錯誤?謝謝
uj5u.com熱心網友回復:
您需要將“presence_of_element_located”方法更改為“visibility_of_element_located”。
舊代碼:
# check if any results found
element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.ID, "noresultsfound"))
改變:
element = WebDriverWait(driver, 5).until(
EC.visibility_of_element_located((By.XPATH, "//*[@id='noresultsfound']"))
)
輸出:
Digram ZQZZQ not found. Need to close modal window!
Modal window hopefully closed
VisibilityOfElementLocated 與 PresenceOfElementLocated:
https://stackoverflow.com/questions/38038920/visibilityofelementlocated-vs-presenceofelementlocated#:~:text=while the visibilityOfElementLocated has to,of presenceOfElementLocated will be enough。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421570.html
標籤:
上一篇:從網站抓取資料
