Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python脚本打开一个页面并单击下载_Python_Selenium_Selenium Chromedriver - Fatal编程技术网

python脚本打开一个页面并单击下载

python脚本打开一个页面并单击下载,python,selenium,selenium-chromedriver,Python,Selenium,Selenium Chromedriver,我试图打开一个页面,点击下载按钮。对于包含download元素的页面,它可以正常工作,但是对于没有该元素的页面,它会引发错误 代码: 它应该通过,而不是引发错误,但当我运行它时,它会说: NoSuchElementException:消息:没有这样的元素:无法定位 要素: {方法:id,选择器:contentplaceholder 1_grdFileUpload_lnkDownload_0} 我如何解决这个问题 from selenium.common.exceptions import NoS

我试图打开一个页面,点击下载按钮。对于包含download元素的页面,它可以正常工作,但是对于没有该元素的页面,它会引发错误

代码:

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

NoSuchElementException:消息:没有这样的元素:无法定位 要素: {方法:id,选择器:contentplaceholder 1_grdFileUpload_lnkDownload_0}

我如何解决这个问题

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()
请注意,即使它按照您的预期工作,它也是低效的,因为您对元素执行了两次搜索

编辑:包含异常的导入语句

更新:作为旁注,假设数据[allurl]中的元素是url,即字符串,则不需要字符串格式。司机,我会的。对于变量名,我是一个糟糕的选择-最好使用更有意义的东西….

driver.find_element_by_id不会像if语句所期望的那样返回True或False。请更改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,则元素可用,否则将转到“其他”条件

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

NameError:未定义名称“NoSuchElementException”。您需要使用从selenium.common.Exception导入它。异常导入NoSuchElementException。我认为这很清楚:-
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