当前位置:   article > 正文

Python——requests模块全解_python request

python request

目录

        安装 requests

         常用属性,方法

        response.text和response.content的区别

通过response.content进行decode,来解决中文乱码——

发送带headers参数请求

        查看浏览器请求头

        发送带参数请求

         法一:网址中带参数

        法二:通过字典params构造参数字典

        在headers参数中携带cookie

        在字典中添加cookie参数

        timeout使用方法

proxies代理参数的使用

        proxies使用方法 

一,request全解

此模块主要用于发送请求获取响应,代码简洁。

  安装 requests

pip install requests

常用属性,方法

案例——通过requests向360导航首页发送请求,获取该页面源码

import requests

# 目标网址
url = "https://hao.360.com/?src=lm&ls=n49dd49049f"

# 发送请求获取响应
response = requests.get(url)

# 查看响应对象的类型
print(type(response))
# 查看响应状态码
print(response.status_code)
# 查看响应内容的类型
print(type(response.text))
# 查看cookies
print(response.cookies)
# 查看响应的内容
print(response.text)

输出——

<class 'requests.models.Response'>
200
<class 'str'>
<RequestsCookieJar[<Cookie __hsid=25cde9ab922daffb for .360.com/>]>
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie6" lang="zh-cn"><![endif]-->
<!--[if IE 7 ]><html class="ie7" lang="zh-cn"><![endif]-->
<!--[if IE 8 ]><html class="ie8" lang="zh-cn"><![endif]-->
<!--[if IE 9 ]><html class="ie9" lang="zh-cn"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html class="" lang="zh-cn"><!--<![endif]-->
<head>
<meta charset="utf-8" />
<title>360导航_一个主页,整个世界</title>
<link rel="dns-prefetch" href="//hao1.qhimg.com"/>
<link rel="dns-prefetch" href="//hao2.qhimg.com"/>

response.text和response.content的区别

response.text:

·类型:str

·解码类型:resquests模块自动根据HTTP头部对响应的编码作出有根据的推测,推测文本编码

response.content:

   ·类型:bytes

·解码类型:无指定,执行挑选

通过response.content进行decode,来解决中文乱码——

·response.content.decode():默认utf-8

·response.content.decode('GBK')

常见编码字符集

·utf-8

·gbk

·asci

·iso-8859-1

案例——

import requests

# 目标网址
url = "https://www.taobao.com/"

# 发送请求获取响应
response = requests.get(url)

# 手动设置编码格式
response.encoding = 'utf8'
# 打印源码的str类型数据
print(response.text)

# response.content是存储的bytes类型的响应数据,进行decode操作
print(response.content.decode('utf-8'))

输出——

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content=&
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/259779
推荐阅读
相关标签
  

闽ICP备14008679号