官方文档:http://docs.python-requests.org/en/master/

  参考文档:http://www.cnblogs.com/zhaof/p/6915127.html#undefined

  参考文档:Python爬虫实例(三)代理的使用

  我这里使用的是当前最新的python3.6。

  安装

    pip3 install requests

  

  使用requests模块完成各种操作

  1、get请求

  

import requests

url='https://www.baidu.com'
r = requests.get(url)
print(r.status_code)

  2、post请求

    url = 'https://www.baidu.com'
data1 = {
"name": "zhaofan",
"age": 23
}
r = requests.post(url, data=data1, verify=True)
print(r.status_code)

  3、使用代理

import requests

url='http://docs.python-requests.org/en/master/'
proxies={
'http':'127.0.0.1:8080',
'https':'127.0.0.1:8080'
}
r = requests.get(url,proxies=proxies)
print(r.status_code)

  如果代理需要设置账户名和密码,只需要将字典更改为如下:
  proxies = {
      "http":"http://user:password@127.0.0.1:9999"
    }
  如果你的代理是通过sokces这种方式则需要pip install "requests[socks]"
  proxies= {
    "http":"socks5://127.0.0.1:9999",
    "https":"sockes5://127.0.0.1:8888"
  }

  4、自定义header和cookie,获取cookie

 url = 'https://weixin.sogou.com/weixin?type=1&s_from=input&query=python&ie=utf8&_sug_=n&_sug_type_='
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36',
'Cookie': 'name=JSESSIONID;value=aaaUrhXY8CzPBgs1eXUFw;domain=weixin.sogou.com'
}
r = requests.get(url, headers=headers)
# 获取cookie
print(r.cookies)
print(r.status_code)
# print(r.text)

  cookie的一个作用就是可以用于模拟登陆,做会话维持

s = requests.Session()
s.get("http://httpbin.org/cookies/set/number/123456")
response = s.get("http://httpbin.org/cookies")
print(response.text)

   5、用户代理池,cookie 池测试代码

import sys
import requests import os
import random sys.path.append(os.path.abspath('{bastpath}{sep}..'.format(bastpath=sys.path[0],sep=os.path.sep)))
class test:
def __init__(self,logPath):
self.mycookies = [
{'name': 'amet non sint', 'value': 'nulla occaecat dolore', 'domain': 'Excepteur labore est proident',
'path': 'dolor laborum consectetur', 'sameSite': 'amet ea Lorem', 'storeId': 'ex nulla nostrud'},
{'name': 'velit consectetur in', 'value': None, 'domain': 'sit',
'path': 'nostrud', 'sameSite': 'et laborum',
'storeId': 'labore commodo elit reprehenderit occaecat'}]
self.user_agent_list = ['Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36',
'Mozilla/5.0 (X11; CrOS i686 3912.101.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0.6',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36',
'Mozilla/5.0 (X11; CrOS i686 3912.101.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'
] # 首先根据关键字获取对应微信公众号的url
def test(self,url):
try:
cookie1 = random.choice(self.mycookies)
print(cookie1)
UserAgent = random.choice(self.user_agent_list)
header = {'User-Agent': UserAgent}
print(header)
txt = requests.get(url, cookies=cookie1,headers=header).text
print(txt)
except Exception as ex:
print(ex)

  

   6、证书验证

  现在的很多网站都是https的方式访问,所以这个时候就涉及到证书的问题

  为了避免这种情况的发生可以通过verify=False,但是这样是可以访问到页面,但是会提示:

  

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs

  解决方法为:

import requests
from requests.packages import urllib3
urllib3.disable_warnings()
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)

  

  7、认证设置

  如果碰到需要认证的网站可以通过requests.auth模块实现

import requests

from requests.auth import HTTPBasicAuth

response = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user",""))
print(response.status_code)

  当然这里还有一种方式

  

import requests

response = requests.get("http://120.27.34.24:9001/",auth=("user",""))
print(response.status_code)

  

  8、异常处理

  关于reqeusts的异常在这里可以看到详细内容:http://www.python-requests.org/en/master/api/#exceptions

  所有的异常都是在requests.excepitons中

  

    从源码我们可以看出RequestException继承IOError,
    HTTPError,ConnectionError,Timeout继承RequestionException
    ProxyError,SSLError继承ConnectionError
    ReadTimeout继承Timeout异常
    这里列举了一些常用的异常继承关系,详细的可以看:http://cn.python-requests.org/zh_CN/latest/_modules/requests/exceptions.html#RequestException

    简单测试

import requests

from requests.exceptions import ReadTimeout,ConnectionError,RequestException

try:
response = requests.get("http://httpbin.org/get",timout=0.1)
print(response.status_code)
except ReadTimeout:
print("timeout")
except ConnectionError:
print("connection Error")
except RequestException:
print("error")

    其实最后测试可以发现,首先被捕捉的异常是timeout,当把网络断掉的haul就会捕捉到ConnectionError,如果前面异常都没有捕捉到,最后也可以通过RequestExctption捕捉到

  9、状态码

  

状态码判断
Requests还附带了一个内置的状态码查询对象
主要有如下内容: 100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',), Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',), Server Error.
500: ('internal_server_error', 'server_error', '/o\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'), 通过下面例子测试:(不过通常还是通过状态码判断更方便)
import requests

response= requests.get("http://www.baidu.com")
if response.status_code == requests.codes.ok:
print("访问成功")

  

  10、文件上传

  实现方法和其他参数类似,也是构造一个字典然后通过files参数传递

import requests
files= {"files":open("git.jpeg","rb")}
response = requests.post("http://httpbin.org/post",files=files)
print(response.text)

python3简单使用requests 用户代理,cookie池的更多相关文章

  1. scrapy 设置cookie池

    代码已经很详细了,可以直接拿来使用了. 包含了: 从网页获取cookie 存入mongodb 定期删除cookie scrapy中间件对cookie池的取用 #!/usr/bin/python #co ...

  2. # Python3微博爬虫[requests+pyquery+selenium+mongodb]

    目录 Python3微博爬虫[requests+pyquery+selenium+mongodb] 主要技术 站点分析 程序流程图 编程实现 数据库选择 代理IP测试 模拟登录 获取用户详细信息 获取 ...

  3. python3 简单实现从csv文件中读取内容,并对内容进行分类统计

    新手python刚刚上路,在实际工作中遇到如题所示的问题,尝试使用python3简单实现如下,欢迎高手前来优化import csv #打开文件,用with打开可以不用去特意关闭file了,python ...

  4. Python简单爬虫Requests

    首先添加库 附配环境变量:安装环境变量 cmd==> 输入指令: path=%path%;C:\Python(Python安装路径) 回车 python2.7版本可能没有pip的话可以先到www ...

  5. python之requests urllib3 连接池

    0.目录 1.参考 2. pool_connections 默认值为10,一个站点主机host对应一个pool (4)分析 host A>>host B>>host A pag ...

  6. python requests 的cookie 操作

    结论: 1.requests模块的请求和响应分别有cookie对象. 可以通过此对象设置和获取cookie. 2.通过在requests.get,requests.post等方法请求中传入cookie ...

  7. Python3.x:requests的用法

    Python3.x:requests的用法 1,requests 比 urllib.request 容错能力更强: 2,通常用法: (1).认证.状态码.header.编码.json r = requ ...

  8. Python3 简单的三级列表思路

    Python3 简单的三级列表思路(初学者 比较low) 代码如下: info = { '北京':{ '沙河':['benz','momo'], '朝阳':['北土城','健德门'], '国贸':[' ...

  9. cookie池的维护

    存储形式: 存储在redis中,“spider_name:username–password":cookie 建立py文件及包含方法: initcookies() 初始化所有账号的cooki ...

随机推荐

  1. Laravel 禁用指定 URL POST 请求的 csrf 检查

    由于在 chrome 插件中使用了跨域请求,所以需要禁用掉 laravel 默认的 post csrf 检查. 配置方法: 在 app/Http/Middleware/VerifyCsrfToken. ...

  2. poj1742 多维背包

    普通的多维背包做不了,需要优化一下 但是没有学优化..别的方法也是可以做的 省去一个 表示阶段的 i 维度,dp[j]表示面值为j的钱是否被凑出来了,used[j]表示第i种硬币在凑面值为j的时候被用 ...

  3. hdu 1596 乘积的最大值

    一般题是 和的最小值 这个是乘积的最大值 Sample Input31 0.5 0.50.5 1 0.40.5 0.4 131 2 //起点 终点2 31 3 Sample Output0.5000. ...

  4. linux命令之grep用法

    grep是linux中很常用的一个命令,主要功能就是进行字符串数据的对比,能使用正则表达式搜索文本,并将符合用户需求的字符串打印出来.grep全称是Global Regular Expression ...

  5. NFS服务自动搭建及挂载脚本

    一.写脚本的动机 由于最近老是搭建NFS,虽然不复杂,但是很繁琐.安装服务.修改配置文件.手动挂载.写入开机自动挂载等于是就写了一个脚本 二.脚本说明及审明 作用:该脚本主要实现NFS自动安装,客户端 ...

  6. Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0 - Round 2)

    Problem A Between the Offices 水题,水一水. #include<bits/stdc++.h> using namespace std; int n; ]; i ...

  7. Linux useradd -M -s

    groupadd mysql #创建mysql分组 useradd -M(不创建主目录) -s(不允许登录) /sbin/nologin mysql -g(加入mysql组) mysql

  8. 自动化部署之gitlab权限管理--issue管理

    一.删除测试项目 先进入项目,选择编辑项目 二.拉取到最下方,移除项目 三 输入你要删除的项目名称 二 创建Group,User,Project 2.1 创建一个组,组名为java Group pat ...

  9. dict 知识汇总

    增: 1. copy 浅复制 2. setdefault (有就查询,没有就添加): 删: 3. clear:清除 4. pop :删除指定键值对 5. popitem :  随机删除一组键值对 改: ...

  10. pandas学习(常用数学统计方法总结、读取或保存数据、缺省值和异常值处理)

    pandas学习(常用数学统计方法总结.读取或保存数据.缺省值和异常值处理) 目录 常用数学统计方法总结 读取或保存数据 缺省值和异常值处理 常用数学统计方法总结 count 计算非NA值的数量 de ...