import urllib2
import urllib
import re
class spilder:
def __init__(self):
self.page=1#初始页是1
self.switch=True#如果是True就开始爬
def loadpage(self):
"""下载页面"""
print u"正在下载页面...."
url="http://www.isocialkey.com/article/list_5_"+str(self.page)+".html"
print url
headers={"User-Agent":" Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"}
request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
html=response.read()
#将正则匹配对象应用到html源码字符串中,返回这个页面的所有段子的列表
pattern=re.compile('<div\sclass="f18 mb20">(.*?)</div>',re.S)
content_list=pattern.findall(html)
#调用dealpage()替换掉段子里的杂七杂八
self.dealpage(content_list)
def dealpage(self,content_list):
"""处理爬来的页面中的段子
content_list:每页的段子列表集合"""
print u"正在处理页面......"
for item in content_list:
#将集合中的每个段子进行处理,替换掉多余的符号
item=item.replace("<p>","").replace("</p>","").replace("<br>","").replace("<br />","")
self.writepage(item)
def writepage(self,item):
"""把每一条段子写入文件里
item:处理后的每一条段子"""
print u"正在保存段子"
#写入文件内
with open("duanzi.txt","a") as f:#a是可读可写,要是用w的话,duanzi.txt中的内容每次都会被下一个覆盖
f.write(item)
def duanzispilder(self):
"""控制爬虫的进行"""
while(self.switch):
self.loadpage()
command=raw_input(("如果继续爬取,请输入回车(退出输入quit)").encode("gb18030"))
if command=="quit":
self.switch=False#变成False就可以结束爬取
self.page+=1#page自加
print u"谢谢使用...."
if __name__=="__main__":
we=spilder()
we.duanzispilder()
爬虫 内涵段子
最新推荐文章于 2019-08-29 17:30:56 发布