本来这个难度很小,没借助框架,自己却写了很久,犯了很多错,话不多说,
直接上代码:
# -*- coding: utf-8 -*-
import urllib
import os
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
url='https://tieba.baidu.com/f?&ie=utf-8'
kw=input('请输入吧名:')
pfn=input('请输入开始页:')
pln=input('请输入结束页:')
pfn=int(pfn)
pln=int(pln)
dir='E:/'
filename=dir+kw
if not os.path.exists(filename):
os.mkdir(dir+kw)
for x in range(pfn,pln+1):
print('第'+str(x)+'页开始下载。。。。。')
data0={
'kw':kw,
'pn':50*(x-1)
}
data1=urllib.parse.urlencode(data0)
total_url=url+data1
response=urllib.request.urlopen(total_url)
with open(filename+'/'+kw+'_'+str(x)+'.html','wb')as f:
f.write((response.read()))
print('第'+str(x)+'页下载结束。。。。。')
看下效果:
请输入吧名:刘备
请输入开始页:1
请输入结束页:5
第1页开始下载。。。。。
第1页下载结束。。。。。
第2页开始下载。。。。。
第2页下载结束。。。。。
第3页开始下载。。。。。
第3页下载结束。。。。。
第4页开始下载。。。。。
第4页下载结束。。。。。
第5页开始下载。。。。。
第5页下载结束。。。。。
当然这些网页都是能够打开的
现在回顾一下犯了哪些低级错误:
1)错误1
HTTP Error 403: Forbidden
在进行爬虫的时候,未加入各种请求头,因此很容易被反爬虫给识别我们是Python程序而不是浏览器
因此需要手动添加:
https://blog.csdn.net/zhou_438/article/details/85035842
2)错误2
print3必须要带括号
https://blog.csdn.net/zhou_438/article/details/85036832
3)错误3
headers不可以省略的
https://blog.csdn.net/zhou_438/article/details/85037196
4)错误4
忘了加上一个item(),因为字典是迭代器对象,无法直接进行用
https://blog.csdn.net/zhou_438/article/details/85037196
5)错误5
居然给一个操作的结果进行赋值
https://blog.csdn.net/zhou_438/article/details/85039555
6)错误6
write居然能拼写错误
https://blog.csdn.net/zhou_438/article/details/85040162
7)错误7
SSL错误
https://www.cnblogs.com/lykbk/p/ASDFQAWQWEQWEQWEQWEQWEQWEQEWEQW.html
8)错误8
mkdir拼写成makedir,心想makedirs是创建多级目录。。。。
9)错误9
路径拼写错误
OSError: [Errno 22] Invalid argument: 'E://E:/2/0.html'