python爬虫学习

用户代理池构建

2017-10-29  本文已影响13人  薛落花随泪绽放
#用户代理池的构建
import urllib.request
import re
import random
uapools=[
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 BIDUBrowser/8.7 Safari/537.36",
]    //这里可以随意加多个浏览器的。

def ua(uapools):
    thisua=random.choice(uapools)
    print(thisua)
    headers=("User-Agent",thisua)
    opener=urllib.request.build_opener()
    opener.addheaders=[headers]
    # 安装为全局
    urllib.request.install_opener(opener) 
for i in range(0,35):
    ua(uapools)
    thisurl="https://www.qiushibaike.com/8hr/page/"+str(i+1)+"/"
    data=urllib.request.urlopen(thisurl).read().decode("utf-8","ignore")
    pat='<div class="content">.*?<span>(.*?)</span>.*?</div>'
    rst=re.compile(pat,re.S).findall(data)
    print(rst)
    for j in range(0,len(rst)):
        print(rst[j])
        print("-------")
上一篇下一篇

猜你喜欢

热点阅读