Python Requests库的使用

Python Requests库的使用

1. requests.get()方法

该方法用于 GET 请求,表示向网站发起请求,获取页面响应对象。语法如下:

res = requests.get(url,headers=headers,params,timeout)

参数说明如下:

  • url:要抓取的 url 地址。
  • headers:用于包装请求头信息。(可以使用F12编程者模式,获取浏览器头部信息)
  • params:请求时携带的查询字符串参数。
  • timeout:超时时间,超过时间会抛出异常。

使用示例:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-129Shpz5-1653534430501)(Python Requests库的使用.assets/image-20220509223740958.png)]

  	data = {
        'tag': '%E7%83%AD%E9%97%A8',
        'from': 'gaia'
    }
    
    response = requests.get('https://movie.douban.com/subject/35258381/',headers=headers, params=data, timeout=1)
    print(response.text) #返回目标网页的源代码
    print(response.headers) #返回头部信息
    print(response.status_code) #返回状态码

这里注意,参数params携带的查询信息也可以直接加在网址后面,上面的代码也可以写成:

response = requests.get(
    'https://movie.douban.com/subject/35258381/?tag=%E7%83%AD%E9%97%A8&from=gaia', 		         headers=headers,
    timeout=1
)

2.requests.post()方法

该方法用于 POST 请求,先由用户向目标 url 提交数据,然后服务器返回一个 HttpResponse 响应对象,语法如下:

response = requests.post(url, headers, params, data={请求体的字典})

示例:

data = {
        'tag': '%E7%83%AD%E9%97%A8',
        'from': 'gaia'
}

response_post = requests.post(
    'https://movie.douban.com/subject/35258381/', 
    headers=headers, 
    data=data
)
print(response.headers) #返回头部信息
print(response.status_code) #返回状态码

sponse.headers) #返回头部信息
print(response.status_code) #返回状态码


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值