pythonurllib库获取yahoo财经数据_Python爬虫之Urllib库使用(一):爬取、保存页面、获取请求信息...

本文介绍了Python内置的HTTP请求库urllib,包括urllib.request模块用于爬虫指定URL,如何下载页面到本地,获取请求信息,以及URL中特殊字符的编码与解码操作。通过实例展示了如何获取Yahoo财经数据。
摘要由CSDN通过智能技术生成

import urllib.request

一、介绍

urllib是Python内置的HTTP请求库,其包括以下模块:

urllib.request:请求模块

urllib.error:异常处理模块

urllib.parse:url解析模块

urllib.robotparser:robot.txt解析模块

二、爬虫指定URL

with urllib.request.urlopen("http://www.baidu.com") as file:

data = file.read() # 读取全部

line = file.readline() # 读取一行

lines = file.readlines() #将全部文件组成一个按行组成的列表并返回

三、下载页面到本地

1.将读取的数据保存到文件中

with open("./1.html","wb") as f:

f.write(data)

2.使用urlretrive直接下载到本地

filename = urllib.request.urlretrieve("http://www.baidu.com","./2.html")

file.info()

四、获取请求信息

1.获取状态码

file.getcode()

200

2.获取url

file.geturl()

'http://www.baidu.com'

3.获取头部信息

file.getheaders()

[('Date', 'Mon, 09 Apr 2018 17:11:24 GMT'),

('Content-Type', 'text/html; charset=utf-8'),

('Transfer-Encoding', 'chunked'),

('Connection', 'Close'),

('Vary', 'Accept-Encoding'),

('Set-Cookie',

'BAIDUID=4B4DEF37A228ED2722DF818D3F4A6C29:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'),

('Set-Cookie',

'BIDUPSID=4B4DEF37A228ED2722DF818D3F4A6C29; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'),

('Set-Cookie',

'PSTM=1523293884; 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=1430_21090_22160; path=/; domain=.baidu.com'),

('P3P', 'CP=" OTI DSP COR IVA OUR IND COM "'),

('Cache-Control', 'private'),

('Cxy_all', 'baidu+230416a5fbb4a587682dea3e4efe4e59'),

('Expires', 'Mon, 09 Apr 2018 17:11:05 GMT'),

('X-Powered-By', 'HPHP'),

('Server', 'BWS/1.1'),

('X-UA-Compatible', 'IE=Edge,chrome=1'),

('BDPAGETYPE', '1'),

('BDQID', '0xab6114e500016321'),

('BDUSERID', '0')]

五、URL中特殊字符处理

使用quote进行编码,再使用unquote进行解码

s = urllib.request.quote("http://www.baidu.com")

s

'http%3A//www.baidu.com'

urllib.request.unquote(s)

'http://www.baidu.com'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值