在采用python查找网页某一元素,不存在的时候会抛出异常,一开始觉得browser.find_element_by_link_text会返回True/Flase,采用if/else 来判断,如下:
if browser.find_element_by_link_text("亲,请登录"):
browser.find_element_by_link_text("亲,请登录").click()
print("请在15秒内完成扫码")
time.sleep(20)
browser.get("https://cart.taobao.com/cart.htm")
else :
print ("cannot found")
但是还是抛出异常:
Traceback (most recent call last):
File "D:/workspace/pycharm/test/miaosha.py", line 64, in <module>
login()
File "D:/workspace/pycharm/test/miaosha.py", line 13, in login
if browser.find_element_by_link_text("亲,请登录"):
File "D:\Program Files\Anaconda3\envs\envs\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 419, in find_element_by_link_text
return self.find_element(by=By.LINK_TEXT, value=link_text)
File "D:\Program Files\Anaconda3\envs\envs\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element
'value': value})['value']
File "D:\Program Files\Anaconda3\envs\envs\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
self.error_handler.check_response(response)
File "D:\Program Files\Anaconda3\envs\envs\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 237, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to find element with link text == 亲,请登录
所以,采用try/except的方式,跳过异常,如下:
browser = webdriver.Ie()
try :
browser.find_element_by_link_text("亲,请登录").click()
print("请在15秒内完成扫码")
time.sleep(20)
browser.get("https://cart.taobao.com/cart.htm")
except :
print ("cannot found")