1. requests模块

1.1 requests简介

requests 是一个功能强大、简单易用的 HTTP 请求库,比起之前用到的urllib模块,requests模块的api更加便捷。(本质就是封装了urllib3)

可以使用pip install requests命令进行安装,但是很容易出网络问题,所以我找了下国内的镜像源来加速。

然后就找到了豆瓣的镜像源:

pip install 包名 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

只要将包名修改一下,就能快速下载模块了。

1.2 requests请求

请求方法有很多种,但是我们只讲最常用的两种:GET请求和POST请求。

1.2.1 GET请求

GET方法用于向目标网址发送请求,方法返回一个Response响应对象,Response下一小节详细讲解。

GET方法的参数:

url:必填,指定请求的URL

params:字典类型,指定请求参数,常用于发送GET请求时使用

例子:

import requests
url = 'http://www.httpbin.org/get'
params = {
'key1':'value1',
'key2':'value2'
}
response = requests.get(url=url,params=params)
print(response.text)

结果:

headers:字典类型,指定请求头部

例子:

import requests
url = 'http://www.httpbin.org/headers'
headers = {
'USER-AGENT':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
response = requests.get(url=url,headers=headers)
print(response.text)

结果:

proxies:字典类型,指定使用的代理

例子:

import requests
url = 'http://www.httpbin.org/ip'
proxies = {
'http':'113.116.127.164:8123',
'http':'113.116.127.164:80'
}
response = requests.get(url=url,proxies=proxies)
print(response.text)

结果:

cookies:字典类型,指定Cookie

例子:

import requests
url = 'http://www.httpbin.org/cookies'
cookies = {
'name1':'value1',
'name2':'value2'
}
response = requests.get(url=url,cookies=cookies)
print(response.text)

结果:

auth:元组类型,指定登陆时的账号和密码

例子:

import requests
url = 'http://www.httpbin.org/basic-auth/user/password'
auth = ('user','password')
response = requests.get(url=url,auth=auth)
print(response.text)

结果:

verify:布尔类型,指定请求网站时是否需要进行证书验证,默认为 True,表示需要证书验证,假如不希望进行证书验证,则需要设置为False

import requests
response = requests.get(url='https://www.httpbin.org/',verify=False)

结果:

但是在这种情况下,一般会出现 Warning 提示,因为 Python 希望我们能够使用证书验证。

如果不希望看到 Warning 信息,可以使用以下命令消除:

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

timeout:指定超时时间,若超过指定时间没有获得响应,则抛出异常

1.2.2 POST请求

POST请求和GET请求的区别就是POST数据不会出现在地址栏,并且数据的大小没有上限。

所以GET的参数,POST差不多都可以使用, 除了params参数,POST使用data参数即可。

data:字典类型,指定表单信息,常用于发送 POST 请求时使用

例子:

import requests
url = 'http://www.httpbin.org/post'
data = {
'key1':'value1',
'key2':'value2'
}
response = requests.post(url=url,data=data)
print(response.text)

结果:

1.3  requests响应

1.3.1 response属性

使用GET或POST请求后,就会接收到response响应对象,其常用的属性和方法列举如下:

response.url:返回请求网站的 URL

response.status_code:返回响应的状态码

response.encoding:返回响应的编码方式

response.cookies:返回响应的 Cookie 信息

response.headers:返回响应头

response.content:返回 bytes 类型的响应体

response.text:返回 str 类型的响应体,相当于response.content.decode('utf-8')

response.json():返回 dict 类型的响应体,相当于json.loads(response.text)

import requests
response = requests.get('http://www.httpbin.org/get')
print(type(response))
# <class 'requests.models.Response'>
print(response.url) # 返回请求网站的 URL
# http://www.httpbin.org/get
print(response.status_code) # 返回响应的状态码
#
print(response.encoding) # 返回响应的编码方式
# None
print(response.cookies) # 返回响应的 Cookie 信息
# <RequestsCookieJar[]>
print(response.headers) # 返回响应头
# {'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Encoding': 'gzip', 'Content-Type': 'application/json', 'Date': 'Mon, 16 Dec 2019 03:16:22 GMT', 'Referrer-Policy': 'no-referrer-when-downgrade', 'Server': 'nginx', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Content-Length': '189', 'Connection': 'keep-alive'}
print(type(response.content))# 返回 bytes 类型的响应体
# <class 'bytes'>
print(type(response.text)) # 返回 str 类型的响应体
# <class 'str'>
print(type(response.json())) # 返回 dict 类型的响应体
# <class 'dict'>

1.3.2 编码问题

#编码问题
import requests
response=requests.get('http://www.autohome.com/news/')
# response.encoding='gbk' #汽车之家网站返回的页面内容为gb2312编码的,而requests的默认编码为ISO-8859-1,如果不设置成gbk则中文乱码
print(response.text)

爬虫(四):requests模块的更多相关文章

  1. 孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块

    孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块 (完整学习过程屏幕记录视频地址在文末) 从今天起开始正式学习Python的爬虫. 今天已经初步了解了两个主要的模块: ...

  2. Python爬虫练习(requests模块)

    Python爬虫练习(requests模块) 关注公众号"轻松学编程"了解更多. 一.使用正则表达式解析页面和提取数据 1.爬取动态数据(js格式) 爬取http://fund.e ...

  3. 网络爬虫之requests模块的使用+Github自动登入认证

    本篇博客将带领大家梳理爬虫中的requests模块,并结合Github的自动登入验证具体讲解requests模块的参数. 一.引入:   我们先来看如下的例子,初步体验下requests模块的使用: ...

  4. 爬虫之requests模块

    requests模块 什么是requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能强大,用法简洁高效.在爬虫领域中占据着半壁江山的 ...

  5. 04.Python网络爬虫之requests模块(1)

    引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档 ...

  6. 06.Python网络爬虫之requests模块(2)

    今日内容 session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 知识点回顾 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 ...

  7. Python 爬虫二 requests模块

    requests模块 Requests模块 get方法请求 整体演示一下: import requests response = requests.get("https://www.baid ...

  8. Python网络爬虫之requests模块(2)

    session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 有些时候,我们在使用爬 ...

  9. Python网络爬虫之requests模块(1)

    引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档 ...

  10. Python网络爬虫之requests模块

    今日内容 session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 知识点回顾 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 ...

随机推荐

  1. 在文件夹下所有文件中查找字符串(linux/windows)

    在linux下可以用 grep "String" filename.txt#字符串 文件名grep -r "String" /home/#递归查找目录下所有文件 ...

  2. 判断一个坐标点是否在封闭曲线内的方法(swift)

    //用playground运行即可 import UIKit var str = "Hello, playground" let lTestPointsOne : [(Double ...

  3. NB-IoT将成为未来5G物联网主流技术

    日前,我国完成了IMT-2020(5G)候选技术方案的完整提交.据悉,在提交的方案中,NB-IoT技术被正式纳入5G候选技术集合,预计2020年6月ITU将正式宣布5G技术方案的诞生.而NB-IoT也 ...

  4. Cesium专栏-大量gltf三维模型加载

    Cesium 是一款面向三维地球和地图的,世界级的JavaScript开源产品.它提供了基于JavaScript语言的开发包,方便用户快速搭建一款零插件的虚拟地球Web应用,并在性能,精度,渲染质量以 ...

  5. 【解决】OCI runtime exec failed......executable file not found in $PATH": unknown

    [问题]使用docker exec + sh进入容器时报错 [root@localhost home]# docker exec -it container-test bash OCI runtime ...

  6. Codeforce612C

    You are given string s consists of opening and closing brackets of four kinds <>,{}, [], (). T ...

  7. intellij idea使用tomcat maven plugin

    环境 java 1.8.0_111 tomcat tomcat-8.5.11 maven 3.2.5 intellij idea 14.0.3 命令行使用 建maven工程 mvn archetype ...

  8. swagger的配置

    // This method gets called by the runtime. Use this method to add services to the container. public ...

  9. Mybatis 报错 java.lang.IllegalArgumentException: Result Maps collection does not contain value for java.lang.Inte

    like ‘%java.lang.IllegalArgumentException: Result Maps collection does not contain value for java.la ...

  10. centos7下ldap+kerberos实现单点登陆

    一. LDAP概念 http://wiki.jabbercn.org/index.php/OpenLDAP2.4%E7%AE%A1%E7%90%86%E5%91%98%E6%8C%87%E5%8D%9 ...