大佬教程收集整理的这篇文章主要介绍了使用IP代理池和用户代理池爬取糗事百科文章,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
import re import random import urllib.request as urlreq import urllib.error as urlerr #用户代理池 uapools = [ "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/59.0.3071.115 Safari/537.36",like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393" ] #ip代理池 ipools = [] #获取用户代理 def get_ua(uapools): thisua = random.choice(uapools) header = ("User-Agent",thisua) url_opener = urlreq.build_opener() url_opener.addheaders = [header] urlreq.install_opener(url_opener) #获取ip池,这里从西刺获取首页IP保存到列表中 def get_ipools(ipurl): get_ua(uapools) data = urlreq.urlopen(ipurl).read().decode("utf-8","ignore") pat = "/></td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>" ret = re.compile(pat,re.S).findall(data) # print(ret) for i in ret: ips = i[0] + ":" + I[1] ipools.append(ips) return ipools #解析糗事百科的文章 def get_article(data): pat = ‘<div class="content">.*?<span>(.*?)</span>.*?</div>‘ rst = re.compile(pat,re.S).findall(data) print(rst) # down_file(rst,i) def get_html(urlweb): for i in range(1,6): #爬取前五页文章 while 1: try: page = urlweb + str(i) thisua = random.choice(uapools) header = ("User-Agent",thisua) #构建用户代理 ip = random.choice(ipools) print("当前使用的ip为" + ip) proxy = urlreq.ProxyHandler({"http": ip}) #构建IP代理 url_opener = urlreq.build_opener(proxy,urlreq.httpHandler) #添加IP代理头 url_opener.addheaders = [header] #添加用户代理头 urlreq.install_opener(url_opener) #设为全局变量 data = urlreq.urlopen(pagE).read().decode("utf-8","ignore") except Exception as e: print(E) ipools.remove(ip) #爬取失败时,从IP池中删除IP,重新爬取文章 conTinue get_article(data) #解析文章 break #完成一页的爬取 if __name__ == "__main__": ipurl = "https://www.xicidaili.com/nn/" ipools = get_ipools(ipurl) #获取ip池 urlweb = "https://www.qiushibaike.com/text/page/" get_html(urlweb)
以上是大佬教程为你收集整理的使用IP代理池和用户代理池爬取糗事百科文章全部内容,希望文章能够帮你解决使用IP代理池和用户代理池爬取糗事百科文章所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。