Python爬虫网页的根本流程:
首先选取一部分精心筛选的种子URL。
将这些URL放入待抓取URL队列。
从待抓取URL队列中读取待抓取队列的URL,解析DNS,并且失去主机的IP,并将URL对应的网页下载下来,存储进已下载网页库中。此外,将这些URL放进已抓取URL队列。
剖析已抓取URL队列中的URL,从已下载的网页数据中剖析出其余URL,并和已抓取的URL进行比拟去重,最初将去重过的URL放入待抓取URL队列,从而进入下一个循环。
1、HTTP申请实现
应用urllib2/urllib实现:
urllib2和urllib是Python中的两个内置模块,要实现HTTP性能,实现形式是以urllib2为主,urllib为辅。
urllib2提供一个根底函数urlopen,通过向指定的URL发出请求来获取数据。最简略的模式是:
import urllib2 response=urllib2.urlopen('http://www.zhihu.com') html=response.read() print html
其实能够将上面对http://www.zhihu.com的申请响应分为两步,一步是申请,一步是响应,模式如下:
import urllib2 # 申请 request=urllib2.Request('http://www.zhihu.com') # 响应 response = urllib2.urlopen(request) html=response.read() print html
还有post申请实现:
import urllib import urllib2 url = 'http://www.xxxxxx.com/login' postdata = {'username' : 'qiye', 'password' : 'qiye_pass'} # info 须要被编码为urllib2能了解的格局,这里用到的是urllib data = urllib.urlencode(postdata) req = urllib2.Request(url, data) response = urllib2.urlopen(req) html = response.read()
将下面的例子改写一下,加上申请头信息,设置一下申请头中的User-Agent域和Referer域信息。2、申请头headers解决
import urllib import urllib2 url = 'http://www.xxxxxx.com/login' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' referer='http://www.xxxxxx.com/' postdata = {'username' : 'qiye', 'password' : 'qiye_pass'} # 将user_agent,referer写入头信息 headers={'User-Agent':user_agent,'Referer':referer} data = urllib.urlencode(postdata) req = urllib2.Request(url, data,headers) response = urllib2.urlopen(req) html = response.read()
urllib2对Cookie的解决也是主动的,应用CookieJar函数进行Cookie的治理。如果须要失去某个Cookie项的值,能够这么做:3、Cookie解决
import urllib2 import cookielib cookie = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) response = opener.open('http://www.zhihu.com') for item in cookie: print item.name+':'+item.value
然而有时候会遇到这种状况,咱们不想让urllib2主动解决,咱们想本人增加Cookie的内容,能够通过设置申请头。
import urllib2 opener = urllib2.build_opener() opener.addheaders.append( ( 'Cookie', 'email=' + "[email protected]" ) ) req = urllib2.Request( "http://www.zhihu.com/" ) response = opener.open(req) print response.headers retdata = response.read()