錯誤信息:
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)