赞
踩
安装 requests
常用属性,方法
response.text和response.content的区别
通过response.content进行decode,来解决中文乱码——
发送带headers参数请求
查看浏览器请求头
发送带参数请求
法一:网址中带参数
法二:通过字典params构造参数字典
在headers参数中携带cookie
在字典中添加cookie参数
timeout使用方法
proxies代理参数的使用
proxies使用方法
此模块主要用于发送请求获取响应,代码简洁。
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"/>
·类型:str
·解码类型:resquests模块自动根据HTTP头部对响应的编码作出有根据的推测,推测文本编码
·类型:bytes
·解码类型:无指定,执行挑选
·response.content.decode():默认utf-8
·response.content.decode('GBK')
·utf-8
·gbk
·asci
案例——
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=&
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。