[英]Python Error Handling With Selenium And Continue Process Again
我正在使用txt文件follow.txt
浏览URL并在网站上单击特定按钮。但是问题是,有时我遇到无法定位元素和无法单击按钮的错误。
我希望如果出现错误,它应该读取txt文件的第二行并忽略该错误。我也尝试了代码来解决问题。但是仍然无法正常工作。我认为我的代码有问题。解决这个问题。这是我用于错误处理的代码。
try:
f = open('follow.txt', 'r', encoding='UTF-8', errors='ignore')
line = f.readline()
while line:
line = f.readline()
browser.get(line)
browser.find_element_by_xpath(""".//*[@id='react-root']/section/main/article/header/div[2]/div[1]/span/button""").click()
time.sleep(50)
f.close();
except Exception as e:
f = open('follow.txt', 'r', encoding='UTF-8', errors='ignore')
line = f.readline()
while line:
line = f.readline()
browser.get(line)
browser.find_element_by_xpath(""".//*[@id='react-root']/section/main/article/header/div[2]/div[1]/span/button""").click()
time.sleep(20)
browser.find_element_by_tag_name("body").send_keys(Keys.ALT + Keys.NUMPAD2)
browser.switch_to_window(main_window)
time.sleep(10)
f.close();
用这种方式,您已经写出了以下问题的答案:“即使在第二行中出现错误,也会发生什么?” 会很吓人。 您绝对不希望像文件中的行数那样写很多嵌套的try除了块。
因此,您将需要尝试除语句中可能会出错的语句以外的语句,否则将允许您使用打开的文件对象而无需重新打开文件。 类似于以下内容:
f = open('follow.txt', 'r', encoding='UTF-8', errors='ignore')
line = f.readline()
while line:
line = f.readline()
browser.get(line)
try:
browser.find_element_by_xpath(""".//*[@id='react-root']/section/main/article/header/div[2]/div[1]/span/button""").click()
except Exception as e:
print e # Or better log the error
time.sleep(50)
browser.find_element_by_tag_name("body").send_keys(Keys.ALT + Keys.NUMPAD2)
browser.switch_to_window(main_window)
time.sleep(10)
f.close();
即使在“ .click()”时发生错误,这也应使您继续下一行。 请注意,当您还没有完成从文件中读取所需内容时,就不想关闭文件。
我打算将“尝试除其他”深入逻辑,但这并不意味着您不应该在其他情况下使用“尝试除其他”,例如在打开文件时。 更好的方法是使用“ with”,在这种情况下,您甚至不必担心在打开文件时关闭文件和处理异常。
with open('follow.txt', 'r', encoding='UTF-8', errors='ignore') as f:
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.