代理地址最后驗證日期:2021-11-09
66免費代理網 #推薦
快代理 #推薦
轉載於:https://www.cnblogs.com/hankleo/p/9683671.html
但是很多時候在開發過程中很少開發者,會使用復制粘貼的形式將代理ip保存到一個列表里面。
直接存到列表的方式好處是直接方便。缺點也很明顯:1.可使用的ip有限。2.代理ip也會面臨失效的可能。
在我實際的開發測試使用的時候,個人更偏向於實時爬取有效的代理ip做爬蟲。下面將使用快代理作為例子。
import time import requests import random from bs4 import BeautifulSoup IP_POOL = [] def get_max_proxy(): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36", "Host": "www.kuaidaili.com", "origin": "https://www.kuaidaili.com" } html = requests.get(url="https://www.kuaidaili.com/free/inha/1/", headers=headers).text soup = BeautifulSoup(html,"lxml") div = soup.find_all(name="div",attrs={"id":"listnav"}) max = 1 for d in div: for num in d.find_all(name="a"): if int(num.text) > max:max = int(num.text) return max def get_proxy_list(max): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36", "Host": "www.kuaidaili.com", "origin": "https://www.kuaidaili.com" } for i in range(1,max): if i>3:return IP_POOL#調試限制使用3個 time.sleep(0.2*random.randint(1,5)) html = requests.get(url="https://www.kuaidaili.com/free/inha/{}/".format(i), headers=headers).text soup = BeautifulSoup(html,"lxml") tbody =soup.find_all(name="tbody") for tb in tbody: for t in tb.find_all(name="td",attrs={"data-title":"IP"}): IP_POOL.append(t.text) return IP_POOL max=get_max_proxy() IP_POOL=get_proxy_list(max) print(len(IP_POOL)) print(IP_POOL)