2016.9.11
本文档代码参考:http://cuiqingcai.com/990.html,在此基础上增加了显示条数的设置。
Python版本:2.7
相关知识点学习
一、urllib2库
1、扒下网页源代码
import urllib2
response = urllib2.urlopen("http://www.baidu.com")
print response.read()
print response.read()
二、请求加上头信息,伪装成浏览器访问
在网页按F12->network,点击第一个请求,查看headers,可看到General
、Response Headers
、Request Headers
三个分类,有
Request URL: https://www.zhihu.com/
Request Method:GET
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
等等参数。
其中,agent
就是请求的身份,如果没有写入请求身份,那么服务器不一定会响应,所以可以在headers
中设置agent
三、input VS raw_input
1、这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。
2、raw_input() 将所有输入作为字符串看待,返回字符串类型。而 input() 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float );同时,input() 可接受合法的 python 表达式,举例:input( 1 + 3 ) 会返回 int 型的 4 。
# -*- coding:utf-8 -*- # -*- coding: utf-8 -*- #coding:utf-8 import urllib import urllib2 import re import thread import time class QSBK: def __init__(self): self.pageIndex = 1 self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = {'User-Agent': self.user_agent} # 存放段子的变量,每一个元素是每一页的段子们 self.stories = [] # 存放程序是否继续运行的变量 self.enable = False # 设置每次读取的次数,默认是1 self.ReadNum = 1 def getPage(self, pageIndex): try: url = 'http://www.qiushibaike.com/hot/page/' + str(pageIndex) request = urllib2.Request(url, headers=self.headers) response = urllib2.urlopen(request) # 将页面转化为UTF-8编码 pageCode = response.read().decode('utf-8') return pageCode except urllib2.URLError, e: if hasattr(e, "reason"): print u"连接糗事百科失败,错误原因", e.reason return None # 传入某一页代码,返回本页不带图片的段子列表 def getPageItems(self, pageIndex): pageCode = self.getPage(pageIndex) if not pageCode: print "页面加载失败...." return None pattern = re.compile('<div.*?author clearfix">.*?<a.*?<img.*?<h2>(.*?)</h2>.*?<div.*?' + 'content">(.*?)</div>.*?<div class="stats.*?class="number">(.*?)</i>.*?' + 'cmt-god.*?main-text">(.*?)</div>', re.S) items = re.findall(pattern, pageCode) # 用来存储每页的段子们 pageStories = [] # 遍历正则表达式匹配的信息 for item in items: # item[0]是一个段子的发布者,item[1]是内容,item[2]是点赞数,item[3]是神评论 # 删除strip()开头结尾处的空白 pageStories.append([item[0].strip(), item[1].strip(), item[2].strip(), item[3].strip()]) return pageStories # 加载并提取页面的内容,加入到列表中 def loadPage(self): # 如果当前未看的页数少于2页,则加载新一页 if self.enable == True: if len(self.stories) < 2: # 获取新一页 pageStories = self.getPageItems(self.pageIndex) # 将该页的段子存放到全局list中 if pageStories: self.stories.append(pageStories) # 获取完之后页码索引加一,表示下次读取下一页 self.pageIndex += 1 # 调用该方法,每次敲回车打印输出一个段子 def getOneStory(self, pageStories, page,Num): tmp = Num input = raw_input() if input == "Q": self.enable = False return # 遍历一页的段子 for story in pageStories: tmp -= 1 if tmp==0: input = raw_input() if input == "Q": self.enable = False return tmp = Num self.loadPage() # 如果输入Q则程序结束 print u"第%d页\t发布人:%s\t点赞数:%s\n内容:%s\n神评论%s\n" % (page, story[0], story[2], story[1], story[3]) # 开始方法 def start(self): print u'请设置每次阅读的条数' self.ReadNum = input() print u"正在读取糗事百科,按回车查看新段子,Q退出" # 使变量为True,程序可以正常运行 self.enable = True # 先加载一页内容 self.loadPage() # 局部变量,控制当前读到了第几页 nowPage = 0 while self.enable: if len(self.stories) > 0: # 从全局list中获取一页的段子 pageStories = self.stories[0] # 当前读到的页数加一 nowPage += 1 # 将全局list中第一个元素删除,因为已经取出 del self.stories[0] # 输出该页的段子 self.getOneStory(pageStories, nowPage,self.ReadNum) spider = QSBK() spider.start()