捕获异常并继续循环以继续使用python进行Web搜索

时间:2018-03-27 12:45:15

标签: python

当我尝试从搜索栏中的值列表中搜索数据时,我遇到异常。我想捕获这些异常并继续循环的其余部分。有没有办法可以做到这一点。我有两种例外,一种在搜索栏上方,一种在下面。我目前正在使用selenium登录并获取必要的详细信息

错误消息:  在搜索栏上方

our search returned more than 100 results. Only the first 100 results will be displayed. Please select 'Reset' and refine the search criteria for specific results. (29)

Employer Number is not a valid . Minimum length should be 8. (890)

搜索栏下方的错误消息。

No records found...

这是我的代码:

for i in ids:
        driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[16]/td[1]/a').click()
        driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[4]/td[3]/a').click()
        # searching for an id.
        driver.find_element_by_xpath('//*[@id="ctl00_ctl00_cphMain_cphMain_txtEmprAcctNu"]').send_keys(i)
        driver.find_element_by_id('ctl00_ctl00_cphMain_cphMain_btnSearch').click()
        driver.find_element_by_xpath('//*[@id="ctl00_ctl00_cphMain_cphMain_grdAgentEmprResults"]/tbody/tr[2]/td[1]/a').click()
        #navigating to the employee details
        driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[8]/td[3]/a').click()
        driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[4]/td[1]/a').click()

上述代码运行后,如果出现错误或不匹配,我将收到上述异常,代码将关闭。我如何捕获这些异常并继续使用代码。如果我的代码做了类似的事情,我捕获日期的方式将非常有用。

        #copying the and storing the date
        subdate = driver.find_element_by_id('ctl00_ctl00_cphMain_cphMain_frmViewAccountProfile_lblSubjectivityDate').text
        subjectivitydate.append(subdate)
        #exiting current employee details
        driver.find_element_by_id('ctl00_ctl00_cphMain_ULinkButton4').click()
        sleep(1)

编辑代码:

for i in ids:
    try:
            driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[16]/td[1]/a').click()
            driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[4]/td[3]/a').click()
        # searching for an id.
            driver.find_element_by_xpath('//*[@id="ctl00_ctl00_cphMain_cphMain_txtEmprAcctNu"]').send_keys(i)
            driver.find_element_by_id('ctl00_ctl00_cphMain_cphMain_btnSearch').click()

            driver.find_element_by_xpath('//*[@id="ctl00_ctl00_cphMain_cphMain_grdAgentEmprResults"]/tbody/tr[2]/td[1]/a').click()
        #navigating to the employee profile
            driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[8]/td[3]/a').click()
            driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[4]/td[1]/a').click()
        #copying the and storing the date
            subdate = driver.find_element_by_id('ctl00_ctl00_cphMain_cphMain_frmViewAccountProfile_lblSubjectivityDate').text
            subjectivitydate.append(subdate)
        #exiting current employee details
            driver.find_element_by_id('ctl00_ctl00_cphMain_ULinkButton4').click()
            sleep(1)
    except:
        continue

如何重启循环? 问候, 任

0 个答案:

没有答案