Python爬取免费ip并检测ip是否有效

mac2024-09-28  54

自己写爬虫的过程中遇到了被封Ip的情况,迫于无奈==,学习了代理Ip的方法 废话不多说,直接上代码 爬取的免费ip网站是 XiciDaili.com

from bs4 import BeautifulSoup import requests f=open(r"C:\Users\thunderobot\Desktop\ip_pool.txt","w",encoding='utf-8') header ={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'} for i in range(1,4): url = "https://www.xicidaili.com/nn/{}".format(str(i)) test_url ="http://www.baidu.com/"#百度作为测试网站 strhtml= requests.get(url,headers=header) if strhtml.status_code == 200:#网页正常访问 soup = BeautifulSoup(strhtml.text,'lxml') ip_table = soup.find('table', {'id': 'ip_list'}) ip = ip_table.find_all('tr')#返回所有tr标签的 for j,tr in enumerate(ip): if j>0: #列表中第一个元素数据无用 td=tr.find_all('td') #下面是获取到的ip地址,赋值到dizhi dizhi = "{}:{}".format(td[1].string,td[2].string) #print(dizhi) #下面的http和https表示协议类型,必须和测试网站匹配 proxy ={ 'http':dizhi, #'https':dizhi, } try: test = requests.get(test_url, headers=header, proxies=proxy, timeout=5) if test.status_code == 200: # 能正常请求目标网页 f.write(dizhi) f.write("\n") except: continue f.close()

下面打开网页,可以看到爬下来的网址已经正确写入文件 但是,免费总归是不好的,即使测试没问题,过几个小时网站上就会更新,前面爬的Ip又会失效,在实际使用中问题很多,有条件可以考虑下阿里云代理,可靠

最新回复(0)