python学习(三)--跟着例子写的贴吧网页爬取
程序员文章站
2022-12-24 12:32:26
from urllib import requestimport urllib#爬贴吧网页文件到本地。首先在本地打开百度贴吧 搜索 java吧#第一页的内容是:http://tieba.baidu.com/f?ie=utf-8&kw=java&fr=search&red_tag=f074629728 ......
from urllib import request
import urllib
#爬贴吧网页文件到本地。首先在本地打开百度贴吧 搜索 java吧
#第一页的内容是:http://tieba.baidu.com/f?ie=utf-8&kw=java&fr=search&red_tag=f0746297280
#第二页 http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=50
#第三页 http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=100
#第四页 http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=150
#看规律 只有第一页比较特殊 把第一页换成:http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=0 也是可以的
#也就是地址栏实际上是 http://tieba.baidu.com/f?kw=java(如果是中文需要转码)&ie=utf-8&pn=0(格式为:(页数-1)*50)
def load_file(url, fname):
print("正在下载:"+fname)
# 水果手机的safari
header = {"user-agent":
"mozilla/5.0 (iphone; u; cpu iphone os 4_3_3 like mac os x; en-us) applewebkit/533.17.9 (khtml, like gecko) version/5.0.2 mobile/8j2 safari/6533.18.5"}
req = request.request(url, headers=header)
#这里是read方法 就读取到了原始网页 开始加了decode方法,结果报类型错误。decode方法把内容解析成了一个字符串
data = request.urlopen(req).read()
return data
def spider(url, begin, end, filename):
#rang函数 理解的类似于java的字符串切割的包左不包右原则,所以需要+1
for page in range(begin, end+1):
url = url +str((page-1)*50)
fname = filename +str(page) +"页.html"
html = load_file(url, fname)
writepage(html, fname)
def writepage(html, fname):
print("正在保存:"+fname)
#存放位置
targetloaction = "d:\浏览器下载目录\images" + "\\"+fname
print("保存文件为:"+targetloaction)
with open(targetloaction, "wb") as f:
f.write(html)
print(fname+"爬取成功")
if __name__ == "__main__":
name = input("请输入要爬取的贴吧名:")
begin = int(input("请输入起始页:"))
end = int(input("请输入尾页:"))
if int(begin) > int(end) :
print("起始页不可大于尾页")
quit()
#组装url
kw = urllib.parse.urlencode({"kw":name})
url = "http://tieba.baidu.com/f?kw="+kw+"&ie=utf-8&pn="
filename = "爬取"+name+"吧第"
spider(url, begin, end, filename);