Python 官方文档:入门教程 => 点击学习
目录urlib 介绍Requests 介绍无需参数直接请求单个页面带参数的 GET 请求发送 POST 请求python 网络请求模块 urllib 、requests Python
python 网络请求模块 urllib 、requests
Python 给人的印象是抓取网页非常方便,提供这种生产力的,主要依靠的就是 urllib、requests这两个模块。
Requests 是一个简单易用的,用Python编写的HTTP库。这个库让我们能够用简单的参数就完成HTTP请求,而不必像 urllib 一样自己指定参数。同时能够自动将响应转码为Unicode,而且具有丰富的错误处理功能。
以下为一些示例代码,本文环境为 Python 3.6
import urllib
from urllib.request import request
from urllib.urlopen import urlopen
# import urllib2
import requests
# 使用 urllib 方式获取
response = urllib.request.urlopen('http://www.baidu.com')
# read() 读取的是服务器的原始返回数据 decode() 后会进行转码
print(response.read().decode())
# 使用 requests 方式获取
# request 模块相比
resp = requests.get('http://www.baidu.com')
print(resp)
print(resp.text)
HTTP 是基于请求和响应的工作模式,urllib.request 提供了一个 Request 对象来代表请求,因此上面的代码也可以这么写
req = urllib.request.Request('http://www.baidu.com')
with urllib.request.urlopen(req) as response:
print(response.read())
Request对象可以增加header信息
req = urllib.request.Request('http://www.baidu.com')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWEBKit/536.26 (Khtml, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with urllib.request.urlopen(req) as response:
print(response.read())
或者直接将 header 传入 Request 构建函数。
带有参数的请求和上面的例子本质一样,可以事先拼出URL请求字符串,然后再进行请求。
本例使用了 腾讯 的股票api,可以传入不同的股票代码以及日期,查询对应股票在对应时间的价格、交易信息。
# 使用带参数的接口访问
tencent_api = "http://Qt.gtimg.cn/q=sh601939"
response = urllib.request.urlopen(tencent_api)
# read() 读取的是服务器的原始返回数据 decode() 后会进行转码
print(response.read())
resp = requests.get(tencent_api)
print(resp)
print(resp.text)
urllib 没有单独区分 GET 和 POST 请求的函数,只是通过 Request 对象是否有 data 参数传入来判断。
import urllib.parse
import urllib.request
url = 'http://www.someserver.com/cgi-bin/reGISter.cgi'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
the_page = response.read()
到此这篇关于Python网络请求模块urllib与requests使用介绍的文章就介绍到这了,更多相关Python urllib与requests内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Python网络请求模块urllib与requests使用介绍
本文链接: https://www.lsjlt.com/news/120708.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0