实例-使用正则表达式的爬虫
正则表达式使用,详见:python学习 正则表达式-match、search、findall、sub、replace/贪婪与非贪婪
例子:
1 from urllib import request 2 import re 3 4 class wadzSpider(): 5 def __init__(self): 6 # 初始化起始页位置 7 self.page=1 8 # 爬取开关,如果为True继续爬取 9 self.switch=True 10 11 #下载页面 12 def loadPage(self): 13 url='http://www.waduanzi.com/page/'+str(self.page) 14 header={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"} 15 a=request.Request(url,headers=header) 16 html=request.urlopen(a).read().decode('utf-8') 17 # print(type(html)) 18 # print(html) 19 #将正则匹配对象应用到html源码字符串里,返回这个页面里的所有段子的列表 20 content = re.findall(r'<div\sclass="item-content">(.*?)<a', html, re.S) # re.S。它表示 “.” 的作用扩展到整个字符串,包括“\n” #(.*?)非贪婪模式 21 # print(content) 22 23 self.handlePage(content) 24 25 # 处理段子里的杂七杂八 26 def handlePage(self,content): 27 for item in content: 28 item=item.replace(' ','').replace('<br />','') 29 print(item,end='\n----------------\n') 30 self.wirtePage(item) 31 32 def wirtePage(self,item): 33 with open(r'waduanzi.txt','a') as f: 34 f.write(item) 35 36 #控制爬虫运行 37 def startWork(self): 38 # 循环执行,直到 self.switch == False 39 while self.switch: 40 self.loadPage() 41 command=input('如果继续爬取,请按回车(退出输入quit):') 42 if command=='quit': 43 # 如果停止爬取,则输入 quit 44 self.switch=False 45 break 46 # 每次循环,page页码自增1 47 self.page+=1 48 print('谢谢使用!') 49 50 if __name__ == '__main__': 51 sp=wadzSpider() 52 sp.startWork()
posted on 2020-02-29 21:05 cherry_ning 阅读(465) 评论(0) 收藏 举报
浙公网安备 33010602011771号