01爬虫---快速使用Urllib爬取网页

来源:互联网 发布:dvp14ss11ti编程手册 编辑:程序博客网 时间:2024/05/22 15:57

环境使用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.htmlfhandle.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 GMTContent-Type: text/html; charset=utf-8Transfer-Encoding: chunkedConnection: CloseVary: Accept-EncodingSet-Cookie: BAIDUID=D79E4E0D7CE07FA007BE2425E09D89BC:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.comSet-Cookie: BIDUPSID=D79E4E0D7CE07FA007BE2425E09D89BC; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.comSet-Cookie: PSTM=1513610072; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.comSet-Cookie: BDSVRTM=0; path=/Set-Cookie: BD_HOME=0; path=/Set-Cookie: H_PS_PSSID=145821079170012517720719; path=/; domain=.baidu.comP3P: CP=" OTI DSP COR IVA OUR IND COM "Cache-Control: privateCxy_all: baidu+8158bfec4d91e0dabf81725c2629dc8eExpires: Mon, 18 Dec 2017 15:14:03 GMTX-Powered-By: HPHPServer: BWS/1.1X-UA-Compatible: IE=Edge,chrome=1BDPAGETYPE: 1BDQID: 0xbd42c81600029cd3BDUSERID: 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
阅读全文
0 0