【学习笔记】python requests库

编辑器用的PyCharm 库的安装使用的Anaconda 

1.get方法

import requests
response = request.get(url, params)

其中response常用属性有:

r.text    url对应的页面内容

r.status_code    服务器状态码  (200表示链接成功)

r.encoding   从headers 猜测编码方式

r.apparent_encoding 从内容分析编码方式

r.headers 网页headers

r.request.headers 发送的header文件

r.content 返回bytes型数据

r.json() 返回json类型的数据


如果我们爬的网站header中不存在charset ,则会默认编码为'ISO-8859-1'

例如:

>>>import requests
>>>r = requests.get('http://www.baidu.com')
>>>print(r.encoding)
ISO-8859-1

这时候如果我们输入

>>>r.text

则会看到返回的字符串中含有乱码,是因为ISO-8859-1不支持中文,但如果我们输入

>>>r.apparent_encoding
'utf-8'

从内容分析则是使用的utf-8编码。这时候我们就可以用

r.encoding=r.apparent_encoding

来将编码方式用从内容解析的编码方式替换,这时候再输入

>>>r.encoding
'utf-8'

这时候再看r.text就不会出现乱码了。

2.post方法

http://pythonscraping.com/pages/files/form.html

我们会用这个网页来说明。

我们打开网页输入名字然后点击提交后,我们会跳转到另一个网页。

我们用chrome按下F12,会看到两个文本输入的地方的name = 'firstname'和 'lastname'

>>>import requests

>>>url ='http://pythonscraping.com/pages/files/processing.php'
>>>_data = {'firstname': '123', 'lastname': '456'}
>>>r = requests.post(url, data=_data)
>>>print(r.text)

Hello there, 123 456!

这里的url之所以不是form.html是因为我们要post的网页是跳转后的网页。

同样,上传图片也是用的post方法,我们会用 这个网页 来说明。


>>>import requests

>>>url = 'http://pythonscraping.com/files/processing2.php'
>>>_file = {'uploadFile': open('/users/apple/downloads/png/svg.png', 'rb')}
>>>r = requests.post(url, files=_file)
>>>print(r.text)
The file svg.png has been uploaded.

同样,我们这里post的网页是跳转后的网页。


当然我们登陆也是用的post方法,

>>>import requests

>>>url = 'http://pythonscraping.com/pages/cookies/welcome.php'
>>>_data = {'username': '123', 'password': 'password'}
>>>r = requests.post(url, data=_data)
>>>r = requests.get(url, cookies=r.cookies)
>>>print(r.text)

<h2>Welcome to the Website!</h2>
You have logged in successfully! <br><a href="profile.php">Check out your profile!</a>

这里我们要先post我们的信息然后得到cookies,然后利用cookies去get到网页信息。


当然为了省略每次都要输入cookies的操作,requests还可以通过创建session来简化代码。

>>>import requests

>>>s = requests.session()
>>>url = 'http://pythonscraping.com/pages/cookies/welcome.php'
>>>_data = {'username': '123', 'password': 'password'}
>>>r = s.post(url, data=_data)
>>>r = s.get(url)
>>>print(r.text)
<h2>Welcome to the Website!</h2>
You have logged in successfully! <br><a href="profile.php">Check out your profile!</a>

最后来介绍一下下载图片


>>>import requests

>>>r = requests.get('https://www.baidu.com/img/bd_logo1.png')
>>>with open('./img/image.png', 'wb') as f:
>>>    f.write(r.content)
这里图片的链接用的是百度的logo, 这里的'wb'表示以二进制模式写入。

猜你喜欢

转载自blog.csdn.net/Canon__/article/details/79522255