在Python中经过导入urllib2组件,来完成网页的抓取工做。在python3.x中被改成urllib.request。html
爬取具体的过程相似于使用程序模拟IE浏览器的功能,把URL做为HTTP请求的内容发送到服务器端, 而后读取服务器端的响应资源。python
1 import urllib2 2 3 response=urllib2.urlopen('http://gs.ccnu.edu.cn/') 4 html=response.read() 5 print html
将返回的html信息打印出来,这和在网站上右键,查看源码看到的内容是同样的。浏览器经过这些源码,将要现实的内容渲染出来。python3.x
除了"http:",URL一样可使用"ftp:","file:"等等来替代。浏览器
HTTP是基于请求和应答机制的:服务器
客户端提出请求,服务端提供应答。post
一样urllib2,能够经过模拟一个请求,而后将这个请求做为参数传入urlopen中,在读取返回的内容。网站
1 import urllib2 2 3 req=urllib2.Request('http://gs.ccnu.edu.cn/') 4 response2=urllib2.urlopen(req) 5 page=response2.read() 6 print page
模拟ftp请求:编码
1 req=urllib2.Request("ftp://example.com/")
在进行http请求的时候能够作两件事url
有时候咱们在爬取网页的时候,须要提交一个表单,模拟登录或者注册的操做。spa
一般http中经过post操做完成, 而在request时,提交的data表单须要讲过urllib中encode编码成标准的方式。
1 import urllib 2 import urllib2 3 4 url = 'http://www.someserver.com/register.cgi' 5 6 values = {"input1": "SeeKHit", 7 "input2": "123456", 8 "__EVENTTARGET": "btnLogin", 9 "__EVENTARGUMENT": "" } 10 11 data = urllib.urlencode(values) # 编码工做 12 req = urllib2.Request(url, data) # 发送请求同时传data表单 13 response = urllib2.urlopen(req) #接受反馈的信息 14 the_page = response.read() #读取反馈的内容
有时候创建http链接后,服务器会根据浏览器传过去的User-Agent头来,返回不一样的内容给客户端。已达到不一样的显示效果。(如安卓上的uc浏览器,就有一个设置设备标识的,如手机版,电脑版,ipad)
Python支持能够自定义的发送过去的User-Agent头,将自定义的字典做为User-Agent头做为一个参数,建立一个请求。
如下代码,讲User-Agent假装成IE浏览器来,进行访问。
1. 应用程序版本“Mozilla/4.0”表示:你使用Maxthon 2.0 浏览器使用 IE8 内核;
2. 版本标识“MSIE 8.0”
3. 平台自身的识别信息“Windows NT ”表示“操做系统为 Windows”
1 url = 'http://www.someserver.com/register.cgi' 2 user_agent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT)' 3 headers = { 'User-Agent' : user_agent } 4 values = {"input1": "SeeKHit", 5 "input2": "123456", 6 "__EVENTTARGET": "btnLogin", 7 "__EVENTARGUMENT": "" } 8 9 data = urllib.urlencode(values) # 编码工做 10 req = urllib2.Request(url, data, headers) # 发送请求,传data表单,模拟User- 11 response = urllib2.urlopen(req) #接受反馈的信息 12 the_page = response.read() #读取反馈的内容