本教程使用Python语言,需提前安装Pip3 or Pip,例如Linux类的,请在命令行内输入:
| 1
 | sudo apt install python3-pip
 | 
安装
一条命令(临时换源):
Linux:
| 1
 | sudo pip install requests -i https://mirrors.aliyun.com/pypi/simple/
 | 
Windows:
| 1
 | pip install requests -i https://mirrors.aliyun.com/pypi/simple/
 | 
使用
基础{Get请求}
| 12
 3
 4
 5
 6
 
 | import requestsdata = {
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
 }
 response = requests.get('https://bing.com',data=data).text
 print(response)
 
 | 
User-Agent就像是浏览器的身份证,如果是Requests默认的ua的话,对应服务器会拒绝你的爬虫请求,简而言之,拿不到数据,所以我们要获得浏览器的ua。

进阶 {Post请求}

- 带数据的 post
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | import requests
 import json
 
 host = "http://httpbin.org/"
 endpoint = "post"
 url = ''.join([host,endpoint])
 data = {'key1':'value1','key2':'value2'}
 
 r = requests.post(url,data=data)
 
 print (r.text)
 
 | 
- 多文件上传
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | import requests
 import json
 
 host = "http://httpbin.org/"
 endpoint = "post"
 
 url = ''.join([host,endpoint])
 
 files = [
 ('file1',('test.txt',open('test.txt', 'rb'))),
 ('file2', ('test.png', open('test.png', 'rb')))
 ]
 
 r = requests.post(url,files=files)
 print (r.text)
 
 | 
冷门 {Put 请求}
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | import requestsimport json
 url_put = "http://127.0.0.1:8080/"
 headers_put = {
 'Content-Type': "application/json"
 }
 param = {
 'myObjectField': 'hello'
 }
 payload = json.dumps(param)
 response_put = requests.put(url, data=payload, headers=headers_put)
 
 | 
项目实战: 梨视频爬虫
这个项目我以前做过,就直接复制过来啦,摆烂啦 (
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | 
 """
 @author:
 @file: 梨视频爬虫.py
 @time: 2021/7/11 21:48
 @desc:
 """
 import requests
 
 url = "https://www.pearvideo.com/video_1731260"
 headers = {
 "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
 "referer": url,
 }
 contId = url.split("_")[1]
 videoStatusUrl = f"https://video.pearvideo.com/mp4/third/20210603/cont-{contId}-15316010-202041-hd.mp4"
 
 
 resp = requests.get(videoStatusUrl, headers=headers).content
 with open("video.mp4", mode="wb") as file:
 file.write(resp)
 
 
 | 
- 第14行,referer的定义,因梨视频请求头中必须有防盗链,即字典中的referer,如果没有,则获取不到视频数据。
- 第16、17行,通过抓包得知,梨视频的视频直链即为一串固定地址加上视频ID号,只需进行字符串分割即可。
- 第20行,向服务器发起GET请求,注意,.content是获取网页的二进制数据。
总结
这库是真的好用,方便。比Python标准库urllib好N倍不止,平时爬虫爬个电影数据就好,不要太过分。