环境使用python3.5
import urllib.request # 导入模块
一、采用获取网页信息,然后再写入文件中
1、将获取的网页信息
file = urllib.request.urlopen("http://www.baidu.com")
data = file.read() # 读取网页全部内容 赋值给一个字符串变量
dataline = file.readline() # 读取网页一行内容 赋值给列表变量
print(dataline)
print(data)
2、将获取的网页保存到本地
fhandle = open("/home/zyb/crawler/myweb/part4/1.html","wb") # 打开以写入模式打开1.html
fhandle.write(data) # 将获取的data数据写入 文件中
fhandle.close() #关闭文件
二、将网页写入本地文件
1、利用urllib.request.urlretrieve(url, filename = 本地文件地址)
filename = urllib.request.urlretrieve("http://edu.51cto.com",filename="/home/zyb/crawler/myweb/part4/2.html")
2、urlretrieve执行过程中会产生缓存所以需要清除使用urlcleanup()进行清除
urllib.request.urlcleanup()
三、urllib一些常见用法
1、爬取的网页.info()
返回当前环境的相关信息,info()返回
file.info()
"""
Date: Mon, 18 Dec 2017 15:14:32 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: Close
Vary: Accept-Encoding
Set-Cookie: BAIDUID=D79E4E0D7CE07FA007BE2425E09D89BC:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BIDUPSID=D79E4E0D7CE07FA007BE2425E09D89BC; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1513610072; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BDSVRTM=0; path=/
Set-Cookie: BD_HOME=0; path=/
Set-Cookie: H_PS_PSSID=145821079170012517720719; path=/; domain=.baidu.com
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Cache-Control: private
Cxy_all: baidu+8158bfec4d91e0dabf81725c2629dc8e
Expires: Mon, 18 Dec 2017 15:14:03 GMT
X-Powered-By: HPHP
Server: BWS/1.1
X-UA-Compatible: IE=Edge,chrome=1
BDPAGETYPE: 1
BDQID: 0xbd42c81600029cd3
BDUSERID: 0
"""
2、爬取的网页..getcode()
爬取网页的状态
file.getcode()
# 200
3、爬取的网页.geturl()
爬取网页的链接
file.geturl()
# http://www.baidu.com
4、urllib.request.quote()
如果在URL中输入中文或者”:”或者”&”等不符合标准的字符时,需要编码时使用
urllib.request.quote()
url = urllib.request.quote("http://www.sina.com.cn")
print(url)
# http%3A//www.sina.com.cn
5、urllib.request.unquote()
当需要解码时使用
urllib.request.unquote()
url = urllib.request.unquote("http://www.sina.com.cn")
print(url)
# http://www.sina.com.cn