报错信息:
selenium.common.exceptions.TimeoutException: Message: timeout
报错原因:
超时
比如我们有大量ip,去访问某个页面,但我们并不知道ip的稳定性,如果一个ip异常不能使用,可能会导致整个代码停掉,后面无法测试。
这时候就要用selenium自带的异常来解决:
代码:
# -*-encoding: utf-8-*-
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
driver_path = r'E:\Tools\cd\chromedriver.exe'
import time
import pymysql
db = pymysql.connect(host="localhost",
user="root", password="123456", database="ip",
port=3306)
cursor = db.cursor()
def get_request(p):
count = 0
d = 0
for i in p:
i = i.strip()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument('--proxy-server=http://' + i)
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(options=chrome_options, executable_path=driver_path)
driver.set_page_load_timeout(20)
try:
driver.get("https://blog.youkuaiyun.com/s_kangkang_A/article/details/102911301")
s = driver.get_cookies()
if s:
save_to_sql(i)
count += 1
print(count, '成功', i)
else:
d += 1
print(d, "失败", i)
driver.close()
except TimeoutException:
driver.execute_script('window.stop()')
print('timeout')
print(count / 100)
def save_to_sql(i):
sql = """
insert into ips(id,ip) value(null,%s)
"""
cursor.execute(sql, (i))
db.commit()
if __name__ == '__main__':
# 把ip放到s里,类似下面
s = """
178.72.74.40:61901
5.59.145.129:8080
185.42.192.69:8080
116.0.6.97:46604
36.37.112.254:35900
186.159.2.241:43459
1.186.40.2:54754
170.246.152.106:56838
141.223.132.163:80
182.74.40.146:30909
83.164.140.13:8080
"""
s = s.split("\n")[1:-2]
get_request(s)
这样,就会打印timeout,而不是直接停代码了。
可以用的放入数据库,以便后续使用。
判断成功的方法是获取当前页面的cookies,实测可行。
相对稳定的ip来源,分别为:小幻代理,89ip,别抓,直接提取,小幻都崩了。实测可用率在50以上。