我正在用 selenium 抓取網站并發送警報,如果發生特定情況。通常,我的代碼運行良好,但有時網站無法加載元素或網站出現如下錯誤訊息:“抱歉,出了點問題!請重繪 頁面并重試!” 兩次,我的腳本都會等到元素加載完畢,但它們沒有,然后我的程式什么也不做。我通常使用 requests 和 Beautifulsoup 進行網頁抓取,所以我對 selenium 不太熟悉,我不確定如何處理這些錯誤,因為我的代碼不會發送錯誤訊息,只是等待,直到元素加載,這將可能永遠不會發生。如果我手動重繪 頁面,程式會繼續作業。我的想法是這樣的:如果加載時間超過 10 秒,請重繪 頁面并重試。
def get_data():
data_list = []
while len(data_list) < 3:
try:
data = driver.find_elements_by_class_name('text-color-main-secondary.text-sm.font-bold.text-left')
count = len(data)
data_list.append(data)
driver.implicitly_wait(2)
time.sleep(.05)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.CLASS_NAME,
'text-color-main-secondary.text-sm.font-bold.text-left'.format(
str(
count 1)))))
except TimeoutException:
break
text = []
elements = []
for i in range(len(data_list)):
for j in range(len(data_list[i])):
t = data_list[i][j].text
elements.append(data_list[i][j])
for word in t.split():
if '#' in word:
text.append(word)
return text, elements
option = webdriver.ChromeOptions()
option.add_extension('')
path = ''
driver = webdriver.Chrome(executable_path=path, options=option)
driver.get('')
login(passphrase)
driver.switch_to.window(driver.window_handles[0])
while True:
try:
infos, elements = get_data()
data, message = check_data(infos, elements)
if data:
send_alert(message)
time.sleep(600)
driver.refresh()
except Exception as e:
exception_type, exception_object, exception_traceback = sys.exc_info()
line_number = exception_traceback.tb_lineno
print("an exception occured - {}".format(e) " in line: " str(line_number))
uj5u.com熱心網友回復:
您可以使用try和except來克服這個問題。首先,讓我們找到等待時間為 10 秒的元素,如果該元素未呈現您可以重繪 頁面。這是代碼的基本版本
try:
# wait for 10s to load element if it did not load then it will redirect to except block
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME,'text-color-main-secondary.text-sm.font-bold.text-left'.format(str(count 1)))))
except:
driver.refresh()
# locate the elemnt here again
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/313809.html
上一篇:用決議器翻頁
下一篇:pythonbeautifulsoup4seleniumChromeDriverManager[網頁抓取到最后都不起作用]
