Python学习爬虫(2)—requests库

作者:IT小样

requests库真的很强大,实力吹一波。
通过requests库可以发起各种请求,本文对requests库进行简介。

get 和post请求区别

http请求有get,post,put,delete,option等各种。而我们常用的主要是get和post请求。
get和post区别:
1、get的参数放在url中,比如参数为user='admin’以及password=‘123’,url为http://example.com,则形式为:http://example.com?user=‘admin’&password=‘123’;而post请求的参数则放在body之中;相对来说,post比较安全
2、get请求一般是对资源的查询获取,而post请求需要提交数据来获取对应需求

requests库函数介绍

requests.get

以上文提到的get请求的例子,以Python来编写如下:
import requests response = requests.get("http://example.com?user='admin'&password='123'")
或者还有一种方式:

import requests
response = requests.get("http://example.com",params={"user":"admin","password":"123"})

即参数以字典的形式,附在params中。
根据http请求的格式,可知在http请求中,还有headers等其他的组成,添加方法和params相同。

requests.post

直接上代码:

import requests
headers = {"Content-Type":"application/json"}
data = {"user":"user1","pwd":"123"}
response = requests.post("http://example.com",headers=headers,data=data)
print(response.text)
print(response.status_code)
print(response.content) 
print(response.json())

上一篇–python学习爬虫(1)–环境搭建
下一篇–Python学习爬虫(3)–BeautifulSoup入门介绍

发布了39 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_31315135/article/details/88685444
今日推荐