沉沙
2019-10-14
来源 :
阅读 1537
评论 0
摘要:本篇文章探讨了大数据采集之使用IP代理池和用户代理池爬取糗事百科文章,希望阅读本篇文章以后大家有所收获,帮助大家对相关内容的理解更加深入。
本篇文章探讨了大数据采集之使用IP代理池和用户代理池爬取糗事百科文章,希望阅读本篇文章以后大家有所收获,帮助大家对相关内容的理解更加深入。

"
简单使用IP代理池和用户代理池的爬虫
import reimport randomimport urllib.request as urlreqimport 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"", ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, 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)" 本文由职坐标整理发布,学习更多的相关知识,请关注职坐标IT知识库!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号