簡(jiǎn)單使用IP代理池和用戶代理池的爬蟲
成都創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括天心網(wǎng)站建設(shè)、天心網(wǎng)站制作、天心網(wǎng)頁(yè)制作以及天心網(wǎng)絡(luò)營(yíng)銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,天心網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到天心省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
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",
"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池,這里從西刺獲取首頁(yè)IP保存到列表中
def get_ipools(ipurl):
get_ua(uapools)
data = urlreq.urlopen(ipurl).read().decode("utf-8","ignore")
pat = "/>.*?(.*?) .*?(.*?) "
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 = '.*?(.*?).*?'
rst = re.compile(pat, re.S).findall(data)
print(rst)
# down_file(rst, i)
def get_html(urlweb):
for i in range(1, 6): #爬取前五頁(yè)文章
while 1:
try:
page = urlweb + str(i)
thisua = random.choice(uapools)
header = ("User-Agent", thisua) #構(gòu)建用戶代理
ip = random.choice(ipools)
print("當(dāng)前使用的ip為" + ip)
proxy = urlreq.ProxyHandler({"http": ip}) #構(gòu)建IP代理
url_opener = urlreq.build_opener(proxy, urlreq.HTTPHandler) #添加IP代理頭
url_opener.addheaders = [header] #添加用戶代理頭
urlreq.install_opener(url_opener) #設(shè)為全局變量
data = urlreq.urlopen(page).read().decode("utf-8","ignore")
except Exception as e:
print(e)
ipools.remove(ip) #爬取失敗時(shí),從IP池中刪除IP,重新爬取文章
continue
get_article(data) #解析文章
break #完成一頁(yè)的爬取
if __name__ == "__main__":
ipurl = "https://www.xicidaili.com/nn/"
ipools = get_ipools(ipurl) #獲取ip池
urlweb = "https://www.qiushibaike.com/text/page/"
get_html(urlweb)