代碼如下:
跟着我要自學網的《python爬蟲課程》學習的。
import urllib
from urllib import request
import time
from builtins import str
#構造請求頭信息
header={
"User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0"
}
#分析url特點
# http://tieba.baidu.com/f?ie=utf-8&kw=python&fr=search #第一頁
# http://tieba.baidu.com/f?kw=python&ie=utf-8&pn=50 #第二頁
# http://tieba.baidu.com/f?kw=python&ie=utf-8&pn=100 #第三頁
def loadpage(fullurl,filename):
print("正在下載:",filename)
req=request.Request(fullurl,headers=header)
resp=request.urlopen(req).read()
return resp
def writepage(html,filename):
print("正在保存:",filename)
with open(filename,"wb") as f: #"wb"表示二進制,以二進制的形式寫入
f.write(html)
print("---------------------------------------")
def tiebaSpider(url,begin,end):
for page in range(begin,end+1):
pn=(page-1)*50
fullurl=url+"&pn="+str(pn) #每次請求的完整url
filename="e:/第"+str(page)+"頁.html" #每次請求後保存的文件名
html=loadpage(fullurl,filename) #調用爬蟲,爬取網頁
writepage(html,filename) #把獲取到的網頁信息寫入本地
if __name__=="__main__":
kw=input("請輸入貼吧名:")
begin=int(input("請輸入起始頁碼:"))
end=int(input("請輸入結束頁碼:"))
url="http://tieba.baidu.com/f?"
key=urllib.parse.urlencode({"kw":kw})
url=url+key
tiebaSpider(url, begin, end)
time.sleep(10)