c httpclient抓取网页( 一个Python抓取网页的库:urllib与urllib2有什么区别?)

优采云 发布时间: 2022-04-15 22:24

  c httpclient抓取网页(

一个Python抓取网页的库:urllib与urllib2有什么区别?)

  python网络爬虫的初级实现代码,python爬虫

  首先,我们来看一个用于抓取网页的 Python 库:urllib 或 urllib2。

  那么 urllib 和 urllib2 有什么区别呢?

  您可以使用 urllib2 作为 urllib 的扩展。明显的好处就是urllib2.urlopen()可以接受Request对象作为参数,这样就可以控制HTTP Request的头部部分了。

  在做HTTP Request的时候应该尽量使用urllib2库,但是urllib2中并没有加入urllib.urlretrieve()函数和urllib.quote等一系列quote和unquote函数,所以有时候辅助需要 urllib。

  urllib.open() 这里传入的参数必须遵循一些协议,比如http、ftp、file等。例如:

  urllib.open('')

  urllib.open('file:D\Python\Hello.py')

  现在有一个以 gif 格式下载所有图像的 网站 的示例。那么Python代码如下:

  

import re

import urllib

def getHtml(url):

page = urllib.urlopen(url)

html = page.read()

return html

def getImg(html):

reg = r'src="(.*?\.gif)"'

imgre = re.compile(reg)

imgList = re.findall(imgre,html)

print imgList

cnt = 1

for imgurl in imgList:

urllib.urlretrieve(imgurl,'%s.jpg' %cnt)

cnt += 1

if __name__ == '__main__':

html = getHtml('http://www.baidu.com')

getImg(html)

  根据上面的方法,我们可以爬取某些网页,然后提取出我们需要的数据。

  实际上,我们使用 urllib 模块作为网络爬虫是非常低效的。让我们介绍 Tornado Web Server。

  Tornado Web 服务器是一个用 Python 编写的极其轻量级、高度可扩展且非阻塞的 IO Web 服务器软件。著名的 Friendfeed网站 就是使用它构建的。 Tornado 与其他主流 Web 服务器框架(主要是 Python 框架)的不同之处在于它采用了 epoll 非阻塞 IO,响应速度快,可以处理数千个并发连接,尤其适用于实时 Web 服务。

  使用 Tornado Web Server 抓取网页会更高效。

  从 Tornado 的官方网站,也应该安装 backports.ssl_match_hostname。官网如下:

  

import tornado.httpclient

def Fetch(url):

http_header = {'User-Agent' : 'Chrome'}

http_request = tornado.httpclient.HTTPRequest(url=url,method='GET',headers=http_header,connect_timeout=200,request_timeout=600)

print 'Hello'

http_client = tornado.httpclient.HTTPClient()

print 'Hello World'

print 'Start downloading data...'

http_response = http_client.fetch(http_request)

print 'Finish downloading data...'

print http_response.code

all_fields = http_response.headers.get_all()

for field in all_fields:

print field

print http_response.body

if __name__ == '__main__':

Fetch('http://www.baidu.com')

  urllib2的常用方法:

  (1)info()获取网页的Header信息

  (2)getcode()获取网页的状态码

  (3)geturl() 获取传入的 URL

  (4)read() 读取文件内容

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线