使用Python requests发送POST请求后如何读取打印返回的HTML内容
解决方案
直接调用requests响应对象的text属性即可获取返回的HTML文本内容,修改后的代码如下:
url = "https://google.com/recaptcha/api2/demo" with requests.Session() as s: s.headers[ 'User-Agent'] = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0' # 注意:提交表单数据不需要手动设置content-type为application/json,requests会自动匹配正确的请求头,原设置错误可能导致请求失败,建议注释 # s.headers['content-type'] = 'application/json; charset=UTF-8' data = {"g-recaptcha-response": str(captcha["text"])} response = s.post(url, data=data) # 打印返回的HTML文本 print(response.text)
补充说明
- 如果出现中文乱码问题,可先手动指定响应编码再打印:
response.encoding = 'utf-8' print(response.text) - 可先校验请求状态再输出内容,避免异常:
if response.status_code == 200: print(response.text) else: print(f"请求失败,状态码:{response.status_code}")
内容的提问来源于stack exchange,提问作者user15887962
相关产品推荐
相关产品推荐

