使用requests库实现http请求
作者:互联网
1.发送请求
import requests
url = 'http://www.tipdm.com/tipdm/index.html'
rqq = requests.get(url)
In [ ]:
print('响应码:', rqq.status_code)
print('编码:', rqq.encoding)
print('请求头:', rqq.headers)
# print('实体:', rqq.text)
print('实体:', rqq.content)
In [ ]:
print('实体:', rqq.text[:40])
print('实体:', rqq.content[:40])
2.设置编码
In [ ]:
import requests
url = 'http://www.tipdm.com/tipdm/index.html'
rqq = requests.get(url)
rqq.encoding = 'utf-8'
print('实体:', rqq.text)
In [ ]:
print('实体:', rqq.content.decode('utf-8'))
3.自适应编码设置
In [ ]:
import chardet
#chardet库使用detect方法检测给定字符串的编码
chardet.detect(rqq.content)
4.防止连接不稳定
In [ ]:
import requests
url = 'http://www.tipdm.com/tipdm/index.html'
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
'''
为避免因等待服务器响应造成程序永久失去响应,通常需要给程序设置一个时间作为
限制,超过该时间后程序将会自动停止等待。在requests库中通过设置timeout
这个参数实现,超过该参数设定的秒数后,程序会停止等待
'''
rqq = requests.get(url, headers=head, timeout=2.)
rqq.headers
5.完整实例
In [ ]:
import requests
import chardet
url = 'http://www.tipdm.com/tipdm/index.html'
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
rqq = requests.get(url, headers=head, timeout=2.0)
# rqq.encoding = 'utf-8'
rqq.encoding = chardet.detect(rqq.content)['encoding']
rqq.text
6.参考文章
【创作不易,望点赞收藏,若有疑问,请留言,谢谢】
标签:http,请求,rqq,url,tipdm,print,import,requests 来源: https://www.cnblogs.com/dongxuelove/p/16434808.html