3 回答

TA貢獻1829條經驗 獲得超13個贊
driver.find_element_by_id()不返回True或False如您的 if 語句所期望的那樣。要么改變你的 if 語句,要么使用 try/except 語句。
from selenium.common.exceptions import NoSuchElementException
for i in data["allurl"]:
driver.get('{0}'.format(i))
try:
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
button_element.click()
except NoSuchElementException:
pass

TA貢獻1825條經驗 獲得超4個贊
檢查 web 元素的長度計數。如果它大于 0,則元素可用并單擊,否則將轉到 else 條件。
for i in data["allurl"]:
driver.get('{0}'.format(i))
if len(driver.find_elements_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0'))>0:
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
button_element.click()
else:
pass

TA貢獻1831條經驗 獲得超10個贊
from selenium.common.exceptions import NoSuchElementException
try:
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
except NoSuchElementException:
pass
else:
button_element.click()
請注意,即使它按您預期的那樣工作,它也是低效的,因為您對元素執行了兩次搜索。
編輯:包括異常的導入語句
更新:作為旁注,假設中的元素data["allurl"]是 url(即字符串),則不需要字符串格式。driver.get(i)會做。并且i是變量名的糟糕選擇 - 最好使用更有意義的東西......
添加回答
舉報