Python日记——锲而不舍,一只艰难的小爬虫
2017.12.20
上次日记爬了金山词霸的翻译页面,算是实现了小爬虫的第一次尝试。这次我们要向更高的难度发起冲击,我们的口号是“福利,福利,还是福利!”
首先我们把目光指向了新晋女神——迪丽热巴,怎么才能省心又省力的从百度贴吧把女神的照片download下来呢,从贴吧页面返回的html来看,基本上都是以.jpg结尾的
于是我们构造了一个正则表达式:
reg = r'src="(http.*?\.jpg)"'
下午还要上班,先把代码贴上来,晚上再续
import urllib.request import urllib import re import time # from bs4 import BeautifulSoup import socket socket.setdefaulttimeout(20) # 设置socket层的超时时间为20秒 url=input("请输入网址:\n") response=urllib.request.urlopen(url) html=response.read().decode('utf-8') # soup=BeautifulSoup(html,"html.parser") urllist=[] reg = r'src="(http.*?\.jpg)"'#正则表达式,得到图片地址 imgre = re.compile(reg) imglist = re.findall(imgre,html) x=0 for i in imglist: urllib.request.urlretrieve(i,'D:\E\%s.jpg' % x) x=x+1 time.sleep(3) print("success!")
——————————分割线————-——--——————-——————————
中午的代码仅能做到爬取贴吧首页的图片,而且这些图片均非帖子内容中的图片,这自然不能满足大家对福利的需求,于是乎我就想办法找出首页里指向帖子的链接。
一开始单纯的我认为练剑自然是以http开头的,可是找了半天也没找到对应的。于是发挥逆向思维,看看能不能从帖子的地址倒推回去,功夫不负有心人,我发现帖子的地址都是类似“http://tieba.baidu.com/p/5486281883”这种格式的
于是我在帖子首页的html内容里搜索帖子地址后面的数字,果然有收获:
看来只需要构造一个正则表达式就可以找到所有帖子的链接啦。
这里面就用了两层遍历,第一层遍历出首页所有帖子的链接,第二层遍历再下载每个帖子里图片,当然如果有兴趣还可以在帖子的后缀后面试着加“pn=数字”,就能把每一页都翻一遍啦
这里面用到的比较重要的函数我觉得是re模块里的几个函数(findall,compile等等)还有urlretrieve(下载图片全靠它啦)
附两个讲解的链接,介绍的还是很清楚的。
re模块介绍https://www.cnblogs.com/MrFiona/p/5954084.html
urlretrieve介绍http://www.nowamagic.net/academy/detail/1302861
1 import urllib.request 2 import urllib 3 import re 4 import time 5 import socket 6 socket.setdefaulttimeout(20) # 设置socket层的超时时间为20秒 7 url=input("请输入网址:\n") 8 response=urllib.request.urlopen(url) 9 html=response.read().decode('utf-8') 10 urllist=[] 11 x=0 12 def getimg(url): 13 global x 14 response=urllib.request.urlopen(url) 15 html=response.read().decode('utf-8') 16 reg = r'src="(http.*?\.jpg)"'#正则表达式,得到图片地址 17 imgre = re.compile(reg) 18 imglist = re.findall(imgre,html) 19 for i in imglist: 20 urllib.request.urlretrieve(i,'D:\E\%s.jpg' % x) 21 x=x+1 22 time.sleep(2) 23 reg2=r'href="/p/\d+"' 24 urlre=re.compile(reg2) 25 urllist=re.findall(urlre,html) 26 for each in urllist: 27 href=each.split('"')[1] 28 getimg("http://tieba.baidu.com"+href) 29 print("success!")