urllib库(常用)学习:
一、urllib.urlopen()
#爬取百度网页代码
import urllib2
#用rullib2.urlopen()方法打开网址
response = urllib2.urlopen("http://www.baidu.com")
#设置编码为utf-8
print response.read().decode('utf8','ignore').encode('gbk','ignore')
二、urllib.urlretrieve(url)
将URL定位到html文件下载到本地硬盘中,如果不指定路径,则会存为临时文件。
import urllib
#将百度首页下载到指定的filename;
response=urllib.urlretrieve('http://www.baidu.com','d:/zxt.html')
print type(response)#元组
print response[0]#文件存储路径
print response[1]#头信息
三、urllib.urlcleanup()
清除urlretrieve中的缓存
四、构造Request(‘R’大写)
import urllib2
response = urllib2.urlopen(request)
print response.read()
类似与前文的“一”,加上Request逻辑上比较清晰;
五、使用getcode()获取网页状态码,使用geturl()获取网页地址
使用urllib.request.quote()进行编码
相反urllib.request.unquote()进行解码
六、URLError
产生的原因:
1.本机无法联网
2.连接不到想要连接的服务器
3.服务器不存在
通常用try...except使用;
importurllib2
request= urllib2.Request('http://blog.csdn.net/qq_38698632')
try:
urllib2.urlopen(reqquest)
except urllib2.URLError, e:
if hasattr(e,"reason"):
print e.reason
else:
print "OOOOOOOOOOK"