用Python来抓取网页是很容易的,前面也写过很多类似的内容,但在Python3.0中,内容多多少少有些不同,下面进行一下介绍.
简单的抓取网页:
- import urllib.request
- url="http://google.cn/"
- response=urllib.request.urlopen(url)
- page=response.read()
这样虽然简单,但如果需要进一步精细的控制就略显不足了,在Python 3.0中,将2.x中urllib和urllib2进行了整合,使得抓取网页变得足够的简单了.具体的,大家都知道,网页抓取实际上分为2步:第一步是发出请求,第二步接收服务器返回的数据,在Python中也是这么做的.
- import urllib.parse
- import urllib.request
- url="http://liuxin-blog.appspot.com/messageboard/add"
- values={"content":"命令行发出网页请求测试"}
- data=urllib.parse.urlencode(values)
- #创建请求对象
- req=urllib.request.Request(url,data)
- #获得服务器返回的数据
- response=urllib.request.urlopen(req)
- #处理数据
- page=response.read()
上面的是POST的数据,众所周知,还有一种GET的,怎么做了?
- import urllib.parse
- import urllib.request
- url="http://www.google.cn/webhp"
- values={"rls":"ig"}
- data=urllib.parse.urlencode(values)
- theurl=url+"?"+data
- #创建请求对象
- req=urllib.request.Request(theurl)
- #获得服务器返回的数据
- response=urllib.request.urlopen(req)
- #处理数据
- page=response.read()
上面2个例子中的response对象有2个常用的方法,geturl(),info()
geturl()的设置是为了辨别是否有服务器端的网址重定向,而info()则包含了一系列的信息.
另外一个重要的内容就是错误处理了,这里错误处理比较简单,贴个代码大家自己琢磨吧
- from urllib.request import Request, urlopen
- from urllib.error import URLError, HTTPError
- req = Request(someurl)
- try:
- response = urlopen(req)
- except HTTPError, e:
- print('The server couldn/'t fulfill the request.')
- print('Error code: ', e.code)
- except URLError, e:
- print('We failed to reach a server.')
- print('Reason: ', e.reason)
- else:
- # everything is fine
最后一个是关于认证的了,网页认证如果大家有相关的网址请发一个过来(没有测试不方便发),关于Cookie认证的以后再写