python | urllib模块

urllib是Python中内置的发送网络请求的一个库(包),在Python2中由urllib和urllib2两个库来实现请求的发送,但是在Python3中已经不存在urllib2这个库了,已经将urllib和urllib2合并为urllib。
urllib是一个库(包),request是urllib库里面用于发送网络请求的一个模块

1.发送一个不携带参数的get请求

import urllib.request
#发起一个不携带参数的get请求
response=urllib.request.urlopen('http://www.baidu.com')
print(response.reason)
#调用status属性可以此次请求响应的状态码,200表示此次请求成功
print(response.status)
#调用url属性,可以获取此次请求的地址
print(response.url)
print(response.headers)
#由于使用read方法拿到的响应的数据是二进制数据,所有需要使用decode解码成utf-8编码
# print(response.read().decode('utf-8'))

2.发送一个携带参数的get请求

import urllib.request
import urllib.parse
#http://www.yundama.com/index/login?username=1313131&password=132213213&utype=1&vcode=2132312

# 定义出基础网址
base_url='http://www.yundama.com/index/login'
#构造一个字典参数
data_dict={
    "username":"1313131",
    "password":"13221321",
    "utype":"1",
    "vcode":"2132312"
}
# 使用urlencode这个方法将字典序列化成字符串,最后和基础网址进行拼接
data_string=urllib.parse.urlencode(data_dict)
print(data_string)
new_url=base_url+"?"+data_string
response=urllib.request.urlopen(new_url)
print(response.read().decode('utf-8'))

3.构造一个携带参数的POST请求

import urllib.request
import urllib.parse
#测试网址:http://httpbin.org/post

#定义一个字典参数
data_dict={"username":"zhangsan","password":"123456"}
#使用urlencode将字典参数序列化成字符串
data_string=urllib.parse.urlencode(data_dict)
#将序列化后的字符串转换成二进制数据,因为post请求携带的是二进制参数
last_data=bytes(data_string,encoding='utf-8')
#如果给urlopen这个函数传递了data这个参数,那么它的请求方式则不是get请求,而是post请求
response=urllib.request.urlopen("http://httpbin.org/post",data=last_data)
#我们的参数出现在form表单中,这表明是模拟了表单的提交方式,以post方式传输数据
print(response.read().decode('utf-8'))

4.补充:

如果直接将中文传入URL中请求,会导致编码错误。我们需要使用quote() ,对该中文关键字进行URL编码

import urllib.request
city=urllib.request.quote('郑州市'.encode('utf-8'))
response=urllib.request.urlopen('http://api.map.baidu.com/telematics/v3/weather?location={}&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'.format(city)) print(response.read().decode('utf-8'))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • urllib and urllib2 区别 –博主提示:下面的是python2中的用法,python3需要做出相应...
    sunnyRube阅读 1,443评论 0 1
  • Get urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返...
    我是帅气的石头阅读 113评论 0 0
  • 学习一门技术,总是要踩好多坑,然后收货一大堆疑惑,这么多相似的方式该学哪个呢?外面公司常用的是哪个呢?就比如pyt...
    徐同学呀阅读 1,881评论 1 11
  • Python语言特性 1 Python的函数参数传递 看两个如下例子,分析运行结果: 代码一: a = 1 def...
    伊森H阅读 3,095评论 0 15
  • 一、概述 urllib2是Python的一个针对URLs的库。他以urlopen函数的形式提供了一个非常简单的...
    MiracleJQ阅读 1,520评论 0 5