python3.6+selenium+phantomJS 網頁爬蟲報錯NoSuchElementException問題及解決方法

錯誤信息:

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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章