Python爬虫 requests库 get/post请求 获取响应内容

import requests
r=requests.get('http://www.lingzhilab.com/resources/getAllRes?page=1')
# u'文本内容'  bytes 类型
print(r.content)

# 获取内容并设置编码
print(r.content.decode('utf-8')) 

# 文本编码
print(r.apparent_encoding) # utf-8

# 响应状态码
print(r.status_code) # 200

# 文本内容
print(r.text)

# JSON解码器
print(r.json())

传递URL参数:

GET请求

import requests
key_dist={'page':1,'page':2}

# 原本url地址:http://www.lingzhilab.com/resources/getAllRes?page=1
r=requests.get('http://www.lingzhilab.com/resources/getAllRes',params=key_dist)

# url正确编码
print(r.url) # http://www.lingzhilab.com/resources/getAllRes?page=2

# u'文本内容'
print(r.text)

POST请求

import requests
import json
key_dist={'page':1,'page':2}

# 原本url地址:http://www.lingzhilab.com/resources/getAllRes?page=1
#r=requests.post('http://www.lingzhilab.com/resources/getAllRes',data=key_dist)

r=requests.post('http://www.lingzhilab.com/resources/getAllRes',data=json.dumps(key_dist)) # json参数

# url正确编码
print(r.url) # http://www.lingzhilab.com/resources/getAllRes

# u'文本内容'
print(r.text)

设置超时时间

秒数设置为0.001秒,会抛出异常,一般会把这个值设置为20秒

import requests
link="http://www.lingzhilab.com/resources/getAllRes?page=1"

# 原本url地址:http://www.lingzhilab.com/resources/getAllRes?page=1
r=requests.get(link,timeout=0.001)

定制请求头

import requests
headers={
'Host': 'www.lingzhilab.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}
r=requests.get('http://www.lingzhilab.com/',headers=headers)
print(r.status_code) # 200

构造session

headers={
'session':'JSESSIONID',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}

reqeusts底层是urllib库

参考:Python3 Requests 模块 - 梦徒 - 博客园

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值