python requests

比urllib.request更方便的爬虫工具

官方中文文档:http://cn.python-requests.org/zh_CN/latest/

  安装

pip install requests
   #
或者用pycharm点点点

  导入模块

>>> import requests

  网页的基本用法,GET,POST,PUT,DELETE,HEAD,OPTIONS

>>> r = requests.get('https://api.github.com/events')
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')

  传递URL参数,url+问号+键值对,例如http://httpbin.org/get?key2=value2&key1=value1
get请求使用params参数
post请求使用data参数

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
#注意字典里值为 None 的键都不会被添加到 URL 的查询字符串里。

#还可以将一个列表作为值传入:
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3

  文本类型响应内容

#Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...

#请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它。如果改变了编码,每当访问 r.text ,Request 都将会使用 r.encoding 的新值。
>>> r.encoding
'utf-8'
>>> r.encoding = 'gb2312'

  二进制响应内容

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

  JSON响应内容

>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

  定制请求头

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

  响应状态码

>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200

#为方便引用,Requests还附带了一个内置的状态码查询对象
>>> r.status_code == requests.codes.ok
True

#如果发送了一个错误请求4XX,5XX,还可以抛出异常
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404

>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error

#当状态码是200时
>>> r.raise_for_status()
None

  响应头

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

#HTTP 头部是大小写不敏感的,可以使用任意大写形式来访问这些响应头字段
>>> r.headers['Content-Type']
'application/json'

>>> r.headers.get('content-type')
'application/json'

  Cookie

#如果某个响应中包含一些 cookie,你可以快速访问它们:
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

#要想发送你的cookies到服务器,可以使用 cookies 参数:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

  重定向和请求历史

#可以使用响应对象的 history 方法来追踪重定向。
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]


#可以通过 allow_redirects 参数禁用重定向处理:
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

  超时

#你可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

  

  

  

初学linux,每学到一点东西就写一点,如有不对的地方,恳请包涵!
原文地址:https://www.cnblogs.com/forlive/p/11471484.html