Python爬虫requests的使用

一些请求方式

1
2
3
4
5
6
import requests
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

基本GET的使用

1
2
3
4
5
import requests

url = 'https://www.baidu.com/'
response = requests.get(url)
print(response.text)

带参数的GET请求

1
如果想查询http://httpbin.org/get页面的具体参数,需要在url里面加上,例如我想看有没有Host=httpbin.org这条数据,url形式应该是http://httpbin.org/get?Host=httpbin.org

下面提交的数据是往这个地址传送data里面的数据。

1
2
3
4
5
6
7
8
9
10
import requests

url = 'http://httpbin.org/get'
data = {
'name':'zhangsan',
'age':'25'
}
response = requests.get(url,params=data)
print(response.url)
print(response.text)

添加header

1
首先说,为什么要加header(头部信息)呢?例如下面,我们试图访问知乎的登录页面(当然大家都你要是不登录知乎,就看不到里面的内容),我们试试不加header信息会报什么错。
1
2
3
4
5
6
import requests

url = 'https://www.zhihu.com/'
response = requests.get(url)
response.encoding = "utf-8"
print(response.text)

提示发生内部服务器错误(也就说你连知乎登录页面的html都下载不下来)。

如果想访问就必须得加headers信息。

image

1
2
3
4
5
6
7
8
import requests

url = 'https://www.zhihu.com/'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}
response = requests.get(url,headers=headers)
print(response.text)

基本POST请求

1
通过post把数据提交到url地址,等同于一字典的形式提交form表单里面的数据
1
2
3
4
5
6
7
8
9
import requests

url = 'http://httpbin.org/post'
data = {
'name':'jack',
'age':'23'
}
response = requests.post(url,data=data)
print(response.text)

结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "23",
"name": "jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "16",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.13.0"
},
"json": null,
"origin": "118.144.137.95",
"url": "http://httpbin.org/post"
}

requests的高级操作

会话维持

1
cookie的一个作用就是可以用于模拟登陆,做会话维持
1
2
3
4
5
import requests
session = requests.session()
session.get('http://httpbin.org/cookies/set/number/12456')
response = session.get('http://httpbin.org/cookies')
print(response.text)

获取cookie

1
2
3
4
5
import requests
response = requests.get('https://www.baidu.com')
print(response.cookies)
for key,value in response.cookies.items():
print(key,'==',value)

文件上传

1
2
3
4
5
import requests
url = "http://httpbin.org/post"
files= {"files":open("test.jpg","rb")}
response = requests.post(url,files=files)
print(response.text)

image

更多具体以后补上,先看看这个

更多的用法

文章目录
  1. 1. 一些请求方式
  2. 2. 基本GET的使用
  3. 3. 带参数的GET请求
  4. 4. 添加header
  5. 5. 基本POST请求
  • requests的高级操作
    1. 1. 会话维持
    2. 2. 获取cookie
    3. 3. 文件上传
  • ,