爬虫入门---Python2和Python3的不同

Python强大的功能使得在写爬虫的时候显得十分的简单,但是Python2和Python3在这方面有了很多区别。

本人刚入门爬虫,所以先写一点小的不同。

以爬取韩寒的一篇博客为例子:

在Python2.7中,我们往往这样写:

import urllib2
request=urllib2.Request("http://blog.sina.com.cn/s/blog_4701280b0102egl0.html")
response=urllib2.urlopen(requset)
print response.read()

但是在Python3中,这样做却行不通了,首先Python3将urllib和urllib2合并成了urllib

而获取网络数据需要urllib.request模块。

其次,由于unicode会导致爬回来的中文乱码,因此需要用str()函数进行对乱码的修改。

因此在Python3中需要这样写:

import urllib.request
url='http://blog.sina.com.cn/s/blog_4701280b0102egl0.html'
response=urllib.request.urlopen(url)
content=response.read()
print (str(content),'utf-8')

 

posted on 2016-04-18 20:09  波比12  阅读(2543)  评论(0编辑  收藏  举报

导航