爬虫的时候遇到封ip的时候可以采用做代理ip继续爬取,甚至可以做一个代理池,随机获取其中的代理ip,不断对目标网站继续爬取
以下是我对https://www.xicidaili.com/nn/这个国内代理网站进行爬取,这个网站中有免费的和付费的代理供我们使用
返回503,说明该网站有反爬机制
为什么会这样,是因为我们请求的太直白,python的requests库对网站请求的默认header是
很明显是一个爬虫,我们将浏览器中的header信息复制过来做成字典形式
headers的字典也可以只加User-Agent的信息
已经可以正常请求到,之后我们设置代理,(python爬虫高级用法中中自带的功能)
将代理网站获取到的ip和端口,写到字典中,但该网站
中有许多ip已经无效,请求时就会无响应,因此设置timeout延时3秒就断开
一个简单的筛选的完整代码:
import requests from bs4 import BeautifulSoup import re #目标网址 for i in range(1,3238): url = "https://www.kuaidaili.com/free/inha/"+str(i)+"/" headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Cookie": "_free_proxy_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFVEkiJTBhODYzOTM2ZjNmZjVlOGVhNDEwN2IyNzdkOTJiYzZhBjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMWFzQVNrTFZzZlBweHpuajZaLy9IK1lMVXdPMUxwazRXQ3ZJcXpxWU0zMDA9BjsARg%3D%3D--3245375dab6a13de635b59428e1ab7dd714bada0; Hm_lvt_0cf76c77469e965d2957f0553e6ecf59=1578794781; Hm_lpvt_0cf76c77469e965d2957f0553e6ecf59=1578794781", "Host": "www.xicidaili.com", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"} response = requests.get(url,headers = headers) html = response.text ips = re.findall('<td data-title="IP">(\d+\.\d+\.\d+\.\d+)</td>',html) ports = re.findall('<td data-title="PORT">(\d+)</td>',html) for ip in zip(ips,ports): proxies = { "http":"http://"+ip[0]+":"+ip[1], "https":"http://"+ip[0]+":"+ip[1], } try: res = requests.get('http://www.baidu.com',proxies=proxies,timeout=3) print(ip,"能使用") with open('ip.txt','a')as f: f.write(":".join(ip)) f.write('\n') except Exception as e: print(ip,"不能使用")
这里给出几个免费的ip代理网站(目前还好使的)
http://www.66ip.cn/1.html
http://www.kuaidaili.com/free/inha/1/
http://www.xicidaili.com/nn/1
http://www.iphai.com/
然后我们利用爬取到的可用代理ip做代理池(随机获取),以下是我爬取补天公益src所有厂家域名的脚本,因为在正常的爬取中如果不加代理,一个ip爬到一定程度(大约200条左右)会被ban掉,所以利用上面的一个脚本,将获取到的可用代理做成代理池,继续爬取
这里我补充一是补天的反爬虫机制比较强,二是免费获取的代理也不够稳定(我买了付费的也不是很稳定),根据我自己测试应该要是能有稳定的代理可以爬取到
归根结底还是太菜了
import requests import re from bs4 import BeautifulSoup import random import threading url = 'https://www.butian.net/Reward/pub' headers={"Cookie":"登陆的cookie", "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36"} def get_random_ip(ip_list): proxy_list = [] for ip in ip_list: proxy_list.append('http://' + ip) proxy_ip = random.choice(proxy_list) proxies = {'http': proxy_ip} return proxies def main(): ip_list = open('ip.txt','r').readlines() proxies = get_random_ip(ip_list) for pnum in range(1,181): r=requests.post(url=url,data={'s':1,'p':pnum},proxies=proxies).json() for info in r["data"]["list"]: company_name = info["company_name"] #print(company_name) company_url = "https://www.butian.net/Loo/submit?cid="+info["company_id"] #print(company_url) html=requests.get(url=company_url,headers=headers,proxies=proxies).text #print(html) soup=BeautifulSoup(html,"lxml") site = re.findall('<input class="input-xlarge" type="text" name="host" placeholder="输入所属域名或ip,若存在多个以,分隔" value="(.*)" />',html) # f = open('yuming.txt','a') # f.write(str(site[0])) # f.write('\n') print(site[0]) if __name__ == "__main__": main()