Python 脚本打开页面,然后单击下载



我正在尝试打开一个页面并单击下载按钮。它适用于具有下载元素的页面,但对于没有该元素的页面,它会引发错误

法典:

for i in data["allurl"]:
driver.get('{0}'.format(i))
if(driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')):
button_element = driver.find_element_by_id('ContentPlaceHolder1_grdFileUpload_lnkDownload_0')
button_element.click()
else:
pass

它应该通过而不是引发错误,但是当我运行它时,它说:

NoSuchElementException: 消息: no suchElement: 无法找到 元素: {"方法":"id","selector":"ContentPlaceHolder1_grdFileUpload_lnkDownload_0"}

我该如何解决这个问题?

driver.find_element_by_id()不会像你的if语句所期望的那样返回TrueFalse。要么更改你的 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

检查 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
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变量名称的选择很糟糕 - 最好使用更有意义的东西......

相关内容

最新更新