from selenium import webdriver
driver = webdriver.Chrome()
driver.set_page_load_timeout(7)
def urlOpen(url):
try:
driver.get(url)
print driver.current_url
except:
return
Run Code Online (Sandbox Code Playgroud)
然后我有 URL 列表并调用上面的方法。
if __name__ == "__main__":
urls = ['http://motahari.ir/', 'http://facebook.com', 'http://google.com']
# It doesn't print anything
# urls = ['http://facebook.com', 'http://google.com', 'http://motahari.ir/']
# This prints https://www.facebook.com/ https://www.google.co.kr/?gfe_rd=cr&dcr=0&ei=3bfdWdzWAYvR8geelrqQAw&gws_rd=ssl
for url in urls:
urlOpen(url)
Run Code Online (Sandbox Code Playgroud)
问题是当网站“ http://motahari.ir/ ”抛出超时异常时,网站“ http://facebook.com ”和“ http://google.com ”总是抛出超时异常。
浏览器一直在等待“motahari.ir/”加载。但循环继续(它不打开“facebook.com”而是等待“motahari.ir/”)并不断抛出超时异常
初始化一个 webdriver 实例需要很长时间,所以我把它从方法中拉出来了,我认为这导致了问题。那么,每当出现超时异常时,我是否应该始终重新初始化 webdriver 实例?如何?(因为我在函数之外初始化了驱动程序,所以我不能在except中重新初始化它)
在继续之前,您只需要清除浏览器的 cookie。(抱歉,我错过了在您之前的代码中看到的内容)
from selenium import webdriver
driver = webdriver.Chrome()
driver.set_page_load_timeout(7)
def urlOpen(url):
try:
driver.get(url)
print(driver.current_url)
except:
driver.delete_all_cookies()
print("Failed")
return
urls = ['http://motahari.ir/', 'https://facebook.com', 'https://google.com']
for url in urls:
urlOpen(url)
Run Code Online (Sandbox Code Playgroud)
输出:
Failed
https://www.facebook.com/
https://www.google.com/?gfe_rd=cr&dcr=0&ei=o73dWfnsO-vs8wfc5pZI
Run Code Online (Sandbox Code Playgroud)
PStry...except...没有明确的异常类型不是很明智,这可能会掩盖不同的意外错误。
| 归档时间: |
|
| 查看次数: |
8782 次 |
| 最近记录: |