一、requests 库使用 需要安装 pip install requests

import requests #导入requests库

request = requests.get("https://www.baidu.com")#发送get请求(url地址)

print(request) #打印响应状态

如果要添加额外的信息 例如 name = germey age = 22

req = reuqests.get("http://httpbin.org/get?name=germey&age=22")

可以简单写

import requests

data = {
'name':'germey',
'age':22
}
req = requests.get("http://httpbin.org/get",params=data) print(req.text)

实际上返回应该是json格式的str 所以直接解析返回结果可以使用json方法

import request

req = request.get("http://httpbin.org/get")
print(type(req.text))
print(req.json())
print(type(req.json()))

调用json()方法 将返回结果是json格式的字符串转化为字典

二、抓取网页 知乎 -> 发现

import requests
import re header={
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
} req = requests.get('https://www.zhihu.com/explore',headers=header)
pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>',re.S)
titles = re.findall(pattern,req.text)
print(titles)

抓取 github 站点图标

import requests

req = requests.get('https://github.com/favicon.ico')
print(req.text)
print(req.content)

前者乱码 后者最前方有个b开头 bytes类型 二进制数据

下载图标 保存本地

import requests

req = requests.get('https://github.com/favicon.ico')

with open('favicon.ico','wb') as f:
f.write(req.content)

三、requests 的 POST请求

import requests

header={
"User-Agent":"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
}
data = {
'name' : 'germey',
'age' : 22
}
req = requests.post('https://httpbin.org/post',data=data,headers=header)
print(req.text)

还有其他属性 状态码(status_code)响应头(headers)Cookies URL 请求历史(history)

内置状态码查询对象 requests.codes

import requests

req = requests.get("http://www.baidu.com")
exit() if req.status_code == requests.codes.ok else print('请求超时')

四、高级用法

1.模拟文件上传

import requests

files = {'file' : open('favicon.ico','rb')}#favicon.ico 文件需要和当前脚本在同一目录下
req = requests.post('http://httpbin.org/post',files=files)
print(req.text)#post 文件上传会有一个files字段标识

2. Cookies

实例 获取cookies过程:

import requests

req = requests.get('https://www.baidu.com')
print(req.cookies)#返回的是RequestCookieJar类型 for key,value in req.cookies.items():#使用items方法 遍历解析
print(key + '=' + value)

cookies 实现维持登录状态 知乎为例:

import requests

headers={
'Cookie' : '_zap=f03025ef-667e-4288-ba1d-fc1a8311d9a2; d_c0="AVCitvzSlA6PTtCufP48PF-2VJaklo6Z_LE=|1543285589"; q_c1=7ae656bc62b1417eb01d68786f1c95be|1543285592000|1543285592000; l_cap_id="ZTNkOWFjYmMyYjYyNDcyMDk0ZGNjYzdjY2NiYTdiYmU=|1543285629|f6cfddf0bfdb7e7797a5e359429512f7072379e2"; r_cap_id="Y2JhYjcwM2RjMzhkNDA2NzgxNjA0MzE1OTIwNmEwOGE=|1543285629|6068d5c01495906fafa897bc23f7563098fba72c"; cap_id="N2IyZDQ3ZjA1ZmQ1NDViZmI1NGVlODE1MDA4MTYyOGU=|1543285629|c1e39a1bdd0e5b2a32737ad30f3bece2217aa952"; _xsrf=1ZwEL7b3KwNuRU6P9mB8xVQoY2m0P53o; capsion_ticket="2|1:0|10:1543913127|14:capsion_ticket|44:NGY3OTBjNTA2Njg2NDk1ZmI4NjhmOTA0MGVhMTE2MWM=|88e9a0b5b2827d4463eb013d17168b3adbe607a8f85b42873020de65594338b2"; z_c0="2|1:0|10:1543913180|4:z_c0|92:Mi4xNDllckN3QUFBQUFCVUtLMl9OS1VEaVlBQUFCZ0FsVk4zSXp6WEFEOUNwUHlVMTNncE1ERHpBS3NaeHBHZEtOTjZn|882987c9d8c0185c0cc6e324a05f27fe8105fa6754142a8e4b93efb98b50519b"; tst=r; __utma=51854390.1171345991.1543913238.1543913238.1543913238.1; __utmz=51854390.1543913238.1.1.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmv=51854390.100--|2=registration_date=20180818=1^3=entry_date=20180818=1; tgw_l7_route=5bcc9ffea0388b69e77c21c0b42555fe',
'Host' : 'www.zhihu.com',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
}
req = requests.get('https://www.zhihu.com',headers=headers)
req.encoding='utf-8'#解决中文乱码
print(req.text)

3.会话维持

requests 直接利用 get() 或者 post() 方法的确可以做到模拟网页的请求,但实际上相当于不同会话
也就是说相当于你用两个浏览器打开了不同的页面

例如 第一次用post登录某网站 第二次想获取登录后的个人信息,又用了一次get请求 相当于打开两个浏览器。
两个完全不相关的会话 能成功获取个人信息吗? 显然不能。
假如两次请求设置一样的cookies不就行了 确实可以 但是太繁琐

更好的解决办法 -> session对象

import requests

requests.get('http://httpbin.org/cookies/set/number/123456')#测试 请求网址 设置cookies
req = requests.get('http://httpbin.org/cookies')#获取cookies
print(req.text)# 返回结果是空的

4.利用session

import requests

s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456')
req = s.get('http://httpbin.org/cookies')
print(req.text)#成功获取

5.SSL证书验证

verify = False

6.代理设置

proxies 参数

例如:

import requests
proxies = {
'http': 'http://127.0.0.1:12345',
'https': 'http://127.0.0.1:12345',
}
requests.get('https://www.taobao.com',proxies=proxies)

如果是 HTTP basic Auth(客户端之前没有认证过,需要输入用户名和密码认证后才可以访问)
示例:

import requests
proxies = {
'http': 'http://user:password@127.0.0.1:12345/',
}
requests.get('https://www.taobao.com',proxies=proxies)

SOCKS协议(网络传输协议,主要用于客户端与外网服务器之间通讯的中间传递)

需要先安装socks库(pip install -U requests[socks])

import requests
proxies = {
'http': 'socks5://user:password@host:port',
'https': 'socks5://user:password@host:port',
}
requests.get('https://www.taobao.com',proxies=proxies)

7.超时设置 timeout参数 也可以写成 timeout(5,11,30) 请求连接5秒,读取接收11秒,总时间30秒 默认None

8.身份认证

import requests
from request.auth import HTTPBasicAuth req = requests.get('http://localhost:',auth=HTTPBasicAuth('username','password'))
print(req.status_code)

简写:

import requests
req = requests.get('http://localhost:',auth=('username','password'))
print(req.status_code)

OAuth认证 (需要安装oauth包(pip intall requests_oauthlib))了解

import requests
from requests_oauthlib import OAuth1 url = 'http://api.twitter.com/1.1/account/verfiy_credentials.json'
auth = OAuth1('YOUR_APP_KEY','YOUR_APP_SECRET','USER_OAUTH_TOKEN','USER_OAUTH_TOKEN_SECRET')
requests.get(url,auth=auth)

9.Prepared request

from requests import Request,Session

url = 'http://httpbin.org/post'

data = {
'name':'germey'
}
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
} s = Session()
req = Request('POST',url,data=data,headers=headers)
prepped = s.prepare_request(req)
r = s.send(prepped)
print(r.text)

Python3编写网络爬虫02-基本请求库requests的使用的更多相关文章

  1. Python3编写网络爬虫01-基本请求库urllib的使用

    安装python后 自带urllib库 模块篇 分为几个模块如下: 1. urllib.request 请求模块 2. urllib.parse 分析模块 3. urllib.error 异常处理模块 ...

  2. Python3编写网络爬虫06-基本解析库Beautiful Soup的使用

    二.Beautiful Soup 简介 就是python的一个HTML或XML的解析库 可以用它来很方便的从网页中提取数据 0.1 提供一些简单的 python式的函数来处理导航,搜索,修改分析树等功 ...

  3. Python3编写网络爬虫07-基本解析库pyquery的使用

    三.pyquery 简介:同样是一个强大的网页解析工具 它提供了和jQuery类似的语法来解析HTML文档,支持CSS选择器,使用非常方便 安装: pip install pyquery 验证: im ...

  4. Python3编写网络爬虫05-基本解析库XPath的使用

    一.XPath 全称 XML Path Language 是一门在XML文档中 查找信息的语言 最初是用来搜寻XML文档的 但是它同样适用于HTML文档的搜索 XPath 的选择功能十分强大,它提供了 ...

  5. python3编写网络爬虫17-验证码识别

    一.验证码识别 1.图形验证码的识别 识别图形验证码需要 tesserocr 库 OCR技术识别(光学字符识别,是指通过扫描字符,然后通过其形状将其翻译成电子文本的过程.)例如 中国知网注册页面 ht ...

  6. python3编写网络爬虫20-pyspider框架的使用

    二.pyspider框架的使用 简介 pyspider是由国人binux 编写的强大的网络爬虫系统 github地址 : https://github.com/binux/pyspider 官方文档 ...

  7. python3编写网络爬虫18-代理池的维护

    一.代理池的维护 上面我们利用代理可以解决目标网站封IP的问题 在网上有大量公开的免费代理 或者我们也可以购买付费的代理IP但是无论是免费的还是付费的,都不能保证都是可用的 因为可能此IP被其他人使用 ...

  8. Python3编写网络爬虫04-爬取猫眼电影排行实例

    利用requests库和正则表达式 抓取猫眼电影TOP100 (requests比urllib使用更方便,由于没有学习HTML系统解析库 选用re) 1.目标 抓取电影名称 时间 评分 图片等 url ...

  9. python3编写网络爬虫21-scrapy框架的使用

    一.scrapy框架的使用 前面我们讲了pyspider 它可以快速的完成爬虫的编写 不过pyspider也有一些缺点 例如可配置化不高 异常处理能力有限对于一些反爬虫程度非常强的网站 爬取显得力不从 ...

随机推荐

  1. C# ABP 允许跨域请求

    备注:无论有没有安装 apb zero模块,都可以使用本文的跨域 首先配置Web Api: 1. 在Web API项目下,安装包 Install-Package Microsoft.AspNet.We ...

  2. [转]webpack4.0.1安装问题和webpack.config.js的配置变化

    本文转自:https://blog.csdn.net/jiang7701037/article/details/79403637 The CLI moved into a separate packa ...

  3. [转]winform利用读取xml获取webconfig

    本文转自:https://www.cnblogs.com/0banana0/archive/2012/02/02/2335727.html 一.利用读取xml获取web.config中的数据库连接 参 ...

  4. MVC应用程序使用Entity Framework

    创建空的MVC应用程序,为了想使用Entity Framework的类库,发现即无法正常引用.如下图,Insus.NET已经明确引了System.Data.Entity(下图Highlight的代码) ...

  5. 关于.net程序集引用不匹配的问题

    今天启动asp.net mvc 程序,其中也用到了web api ,autofac等,为了版本兼容性问题,将mvc和 web api 的版本控制到5.2.0.0,Newtonsoft.Json 的版本 ...

  6. java中带参数的try(){}语法

    带资源的try语句(try-with-resource)的最简形式为: try(Resource res = xxx)//可指定多个资源 { work with res } try块退出时,会自动调用 ...

  7. java 传入list集合 返回树形菜单,for循环遍历

    public List<SysPermissionVO> getTreeMenu(List<SysPermissionVO> list,SysPermissionVO sysP ...

  8. Three.js开发指南---学习使用几何体(第五章)

    一 基础几何体 1 二维图形:二维图形都是基于x和y轴构建的,即展示的形式就是他们都是“直立”的,如果希望这些二维图形躺下,则需要将几何体沿着x轴向后旋转1/4圈 mesh.rotation.x=-M ...

  9. php中parse_url函数解析

    1.在php开发过程中我们经常要用到用户上传文件这个功能,那么用户上传文件我们肯定要知道用户上传文件的合法性,那么我们就要从url中获取文件的扩展名.那么就会用到parse_url()这个函数. pa ...

  10. Git 及 GitHub 使用

    Git bash 的常用命令 1. pwd    查看当前所在目录 2. cd cd ..         返回上一级 cd 目录    进入对应的目录 3. ls      查看当前文件夹的内容  ...