The Agent crawler is implemented by grasping the free proxy IP of the West Thorn Network:
from bs4 import BeautifulSoupimport requestsimport randomimport telnetlibrequests = requests.session()ip_list = []proxy_list = []def get_proxy(): url = ‘http://www.xicidaili.com/nn/‘ headers = { ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36‘ } web_data = requests.get(url, headers=headers) soup = BeautifulSoup(web_data.text, ‘lxml‘) ips = soup.find_all(‘tr‘) for i in range(1, len(ips)): ip_info = ips[i] tds = ip_info.find_all(‘td‘) ip = tds[1].text port = tds[2].text try: telnetlib.Telnet(ip, port, timeout=2) ip_list.append(ip+":"+port) except: pass #print(ip_list) for ip in ip_list: proxy_list.append(‘http://‘ + ip) proxies = get_proxy()proxy_ip = random.choice(proxy_list)proxies = {‘http‘: proxy_ip}print(proxies)
Proxy IP usage, upload him to the GET request.
requests.get(url, headers=headers, proxies=proxies)
Python: Crawl free proxy IP