如何在Selenium中处理特定异常?
我在我的项目中需要使用selenium。当我使用selenium时,我在每一步都这样做:
time.sleep(6)
我给每个页面加载留了足够的时间,但有时候还是会遇到下面的错误。
我大多数时候会遇到一些常规的异常:
Exception: Message: u'Unable to locate element: {"method":"xpath","selector":"//textarea[@style=\\"overflow-y: hidden; height: 50px; width: 300px;\\"]"}' ; Stacktrace: Method WebDriverError threw an error in file:///tmp/tmpBxGp2P/extensions/fxdriver@googlecode.com/resource/modules/atoms.js
Traceback (most recent call last):
File "crawl_optimize.py", line 206, in main
word_query = browser.find_element_by_xpath('//textarea[@style="overflow-y: hidden; height: 50px; width: 300px;"]')
File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 210, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 643, in find_element
{'using': by, 'value': value})['value']
File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 153, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/remote/errorhandler.py", l ine 147, in check_response
raise exception_class(message, screen, stacktrace)
我还因为WebDriverWait().Until()而遇到了“没有这样的实现”错误:
NoSuchElementException: Message: u'Unable to locate element: { "method":"xpath","selector":"//textarea[@style=\\"overflow-y: hidden; height: 50px; width: 300px;\\"]"}' ; Stacktrace: Method WebDriverError threw an error in file:///tmp/tmpBxGp2P/extensions/fxdriver@googlecode.com/resource/modules/atoms.js
keyword : balance transfer ad pos : 2
Exception: Message: None
Traceback (most recent call last):
File "crawl_optimize.py", line 228, in main
start_cpc,end_cpc = set_initial_cpc(initial_max_cpc,ad_position)
File "crawl_optimize.py", line 95, in set_initial_cpc
ep = crawl_position(cost)
File "crawl_optimize.py", line 82, in crawl_position
WebDriverWait(browser, 10).until(lambda driver : driver.find_element_by_link_text(word.lower()))
File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/support/wait.py", line 55, in until
raise TimeoutException()
TimeoutException: Message: None
有什么办法可以解决这些异常吗?
1 个回答
0
可能有两个原因。
- 你的元素在规定的6秒内还没有加载完成。
你的定位器有问题。这个看起来不太对……
{ "method":"xpath","selector":"//textarea[@style=\"overflow-y: hidden; height: 50px; width: 300px;\"]"}'
你能用FireFinder或者类似的工具检查一下这个定位器返回的结果是否符合你的预期吗?
如果定位器没问题,你可以尝试使用WebDriverWait和ExpectedCondition来确认页面已经加载完成,而不是冒险假设你的页面总是在6秒内加载完。