您的位置:首页 > 编程语言 > Python开发

python3.6+selenium+phantomJS 网页爬虫报错NoSuchElementException问题及解决方法

2017-12-06 15:19 736 查看
错误信息:

selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with xpath '//*[@id='**']'","request":{"headers":{"Accept":"application/json",
...
}}
Screenshot: available via screen

由于代码换用Chrome浏览器是正常执行的,所以个人认为原因是由于使用phantomJS后,动态JS还没有解析,没有获取到网页代码,所以才会报NoSuchElementException

所以写一个方法等JS解析就行了


代码如下:

# JS
def wait(driver):
elem = driver.find_element_by_tag_name('html')
count = 0
while True:
count +=1
if count>20:
print('timeout')
return
time.sleep(5)
try:
elem == driver.find_element_by_tag_name('html')
except StaleElementReferenceException:
return在报错的语句前使用wait(driver)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息