官方文档: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. windows下sublime通过sftp扩展上传文件到linux服务器上

    首先在package controll下载sftp扩展,在任意磁盘下新建文件夹: 然后,添加该文件夹到sublime中,并在xhell中链接linux服务器,新建目录,mkdir  /home/hel ...

  2. 浏览器的userAgent归纳

    IE IE6 User-Agent:Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 5.2) IE7 User-Agent:Mozilla/4.0 (compat ...

  3. TLiteSQLMonitor 使用方法

  4. Java集合(Collection)综述

    1.集合简介 数学定义:一般地,我们把研究对象统称为元素.把一些元素组成的总体叫做集合. java集合定义:集合就是一个放数据的容器,准确的说是放数据对象引用的容器. java中通用集合类存放于jav ...

  5. pytest十一:函数传参和 firture 传参数 request

    为了提高代码的复用性,我们在写用例的时候,会用到函数,然后不同的用例去调用这个函数.比如登录操作,大部分的用例都会先登录,那就需要把登录单独抽出来写个函数,其它用例全部的调用这个登录函数就行.但是登录 ...

  6. Jmeter NonGUI模式

    一般情况下我们都是在NonGUI模式下运行jmeter.这样做有两个好处 节省系统资源,能够产生更大的负载 可以通过命令行参数对测试场景进行更精细的配置 示例 创建luzhi.jmx脚本 jmeter ...

  7. python 全栈开发,Day136(爬虫系列之第3章-Selenium模块)

    一.Selenium 简介 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全 ...

  8. django中的null=true,blank=true,这个讲得清楚点

    看mastering django:core,中文名<精通django>里的, 说得在理点. 截个图

  9. 023 SpringMVC拦截器

    一:拦截器的HelloWorld 1.首先自定义拦截器 只要实现接口就行. package com.spring.it.interceptors; import javax.servlet.http. ...

  10. 002 在大数据中基础的llinux基本命令

    一:基本命令 1.显示当前的目录 2.长格式显示目录自身的信息 3.创建文件 4.创建目录 创建多层目录,使用-p. 5.删除目录或者文件 -f:不提示,强制删除 -i:删除前,提示 -r:删除目录以 ...