http请求的部分处理方法

处理方法

对响应头中有类似æµ\x99大ä¸\xadæ\x8e§ECS-700å\x8a\x9fè\x83½å\的中文乱码,重新编码

filename=response.headers['Content-Disposition'].encode('raw_unicode_escape').decode()

截取文件后缀

file_type = filename[filename.rfind('.') + 1:]

对于大文件可以chunk分块下载:

import requests

def file_download(file_url: str, filename: str):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/87.0.4280.88 Safari/537.36',
    }
    res = requests.get(file_url, headers=headers, stream=True)
    with open(filename, 'wb') as f:
        for chunk in res.iter_content(chunk_size=1024 * 10):
            if chunk:
                f.write(chunk)

响应内容转换HtmlResponse使用样式选择器

import requests
from scrapy.http import HtmlResponse

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/72.0.3626.121 Safari/537.36',
}
req_url = 'https://www.baidu.com/'
res = requests.get(req_url, timeout=10, headers=headers)
res = HtmlResponse(req_url, body=res.content.decode(), encoding="utf-8")
print(res.text)

对部分https网站请求报错,在请求中添加 verify=False 参数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_顺其 自然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值