python - requests模块

requests模块

# requests 学习

# 安装
# pip install requests

# 导入模块
import requests

# 访问网页
# res = request.get('URL')
# res = requests.get('http://127.0.0.1:8000/index')

#
# 基本应用
# print(res.text)
# print(res.content)
# res.encoding
# res.apparent_encoding
# res.status_code

# 参数详解
# requests.request()
#     - method 参数: 提交方式
#             GET,POST,PUT,DEL
#     - url    参数: 提交地址
#     - params 参数: 在URL中传递的参数,get

#     - data   参数:在请求体中传递数据(请求头中参数 content-type:application/url-from-...)
#                       请求体中数据: {'a':1,'b':2}字典形式 或者 'a=1&b=2'
#     -  json  参数:在请求体中传递数据(请求头中参数 content-type:application/json)
#                       请求体中数据:{'a':123}字典方式,支持嵌套
#               PS: data方式与 json方式区别在于 字典数据是或否可以支持嵌套

#     - headers 参数:
#             headers={ 参数
#               比较重要的参数 1.浏览器类型 2.使用设备类型,都是在headers中添加的.
#               }

#    -  cookies 参数:
#                 cookies={'cookies':cooikse}

#   -   files 参数
#                 上传文件

#   - auth  参数
#               在headers中加入加密的用户名 和密码

#   - timeout 参数
#               请求和响应的超时时间

#   - allow_redirects 参数
#               是否允许中定向(跳转)

#   - proxies 参数
#               代理

#   - verify 参数
#               是否忽略证书

#   - cert 参数
#               证书,添加证书文件

#   - stream 参数
#               边下边存属性

#   -  session参数:
                # 用于保存客户端的历史访问信息

# 示例:
#     requests.request(
#         method = 'GET',
#         url='http://127.0.0.1:8000/index',
#         params = {'k1':'v1'},
#         data = {'a':1123},
#         json = {'b',123123},
#         headers={......},
#         cookies={'cookies':'values'},
#     )

# 爬虫实例:
#     import  requests
#     from bs4 import BeautifulSoup
#
#     res = requests.get(url="http://www.autohome.com.cn/news/")
#     res.encoding = res.apparent_encoding
#     print(res.text)
#
#     soup = BeautifulSoup(res.text,features='html.parser')
#     target = soup.find(id="auto-channel-lazyload-article")
#     li_list = target.find_all('li')
#
#     for i in li_list:
#         a = i.find('a')
#         if a:
#             print(a.attrs.get('href'))
#             print(type(a))

猜你喜欢

转载自www.cnblogs.com/Anec/p/9719436.html