前言
本章不做过多前期的讲解直接上Requests
有关pip安装或者其他乱七八糟简单语法暂不提供
Requests认知
Tips: 以上认知只是个人对该库的理解,不想看直接去代码自己实操总结自己的一套认知理念。
个人理解Requests库和Scarypy相比Requests不用说肯定相比而言简单很多,刚开始想学爬虫了解了Scarypy发现是个爬站的大框架所以上手就会难点,从简单的开始Requests是爬页面而不是整个站,两者之间最大的区别莫过于此了吧。本章讲解的也只是Requests片面的方法使用,更多的功能后期也会随着时间不断地更新。
传递 URL 参数
你也许经常想为 URL 的查询字符串(query string)传递某种数据。如果你是手工构建 URL,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。例如, httpbin.org/get?key=val。 Requests 允许你使用 params 关键字参数,以一个字符串字典来提供这些参数。举例来说,如果你想传递 key1=value1 和 key2=value2 到 httpbin.org/get
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
通过打印输出该 URL,你能看到 URL 已被正确编码:
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
定制请求头
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
>>> 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
注意: 定制 header 的优先级低于某些特定的信息源,例如:
如果在 .netrc 中设置了用户认证信息,使用 headers= 设置的授权就不会生效。而如果设置了 auth= 参数,.netrc
的设置就无效了。
如果被重定向到别的主机,授权 header 就会被删除。
代理授权 header 会被 URL 中提供的代理身份覆盖掉。
在我们能判断内容长度的情况下,header 的 Content-Length 会被改写。
更进一步讲,Requests 不会基于定制 header 的具体情况改变自己的行为。只不过在最后的请求中,所有的 header 信息都会被传递进去。
注意: 所有的 header 值必须是 string、bytestring 或者 unicode。尽管传递 unicode header 也是允许的,但不建议这样做。
更加复杂的 POST 请求
通常,你想要发送一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
你还可以为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:
>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个 string 而不是一个 dict,那么数据会被直接发布出去。
响应状态码
响应头
我们可以查看以一个 Python 字典形式展示的服务器响应头:
>>> 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 头部而生的。根据 RFC 2616, HTTP 头部是大小写不敏感的。
因此,我们可以使用任意大写形式来访问这些响应头字段:
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json'
它还有一个特殊点,那就是服务器可以多次接受同一 header,每次都使用不同的值。但 Requests 会将它们合并,这样它们就可以用一个映射来表示出来,参见 RFC 7230:
A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.
接收者可以合并多个相同名称的 header 栏位,把它们合为一个 "field-name: field-value" 配对,将每个后续的栏位值依次追加到合并的栏位值中,用逗号隔开即可,这样做不会改变信息的语义。
Requests代码
Code已经做了简单的封装直接拆解调用某个function即可,或者直接使用也行。
#!/usr/bin/python3
#-*- coding:utf-8 -*-
import requests
import time
class website():
def __init__(self,url):
"""This is about requests module usage."""
self.url = url
def _simpleInfo(self):
"""This function is get about site status"""
r = requests.get(self.url)
print("I will write simple code to here.")
print("*"*30)
time.sleep(3)
print("This is site status code: "+str(r.status_code))
print("The module is coding: "+str(r.encoding))
change = r.encoding='utf-8'
print("Changed site type is: "+str(change))
def _getHead(self):
"""This function is get site head info"""
cookies = dict(cookies_are='working')
r = requests.get(self.url, cookies = cookies)
info = [r.headers['server'], \
r.headers['date'], \
r.cookies, \
r.headers['transfer-encoding'], \
r.headers['connection']
]
#print(r.headers)
print("*"*50)
print("Version: %s" %info[0])
print("date: %s" %info[1])
print("Cookies: %s" %info[2])
print("Transfer type: %s" %info[3])
print("Connection: %s" %info[4])
print("*"*50)
def _reWirte(self):
"""This function about for site rewrite."""
r = requests.get(self.url, allow_redirects=False)
"""True 为做跳转False则反之"""
status = [r.url, r.status_code, r.history]
print("site: %s" %status[0])
print("Status: %s" %status[1])
print("Recheck: %s" %status[2])
def _setVariable(self):
"""Set variable to chage site post."""
payload = {'id':'90', 'uid':'7'}
headers = {'user-agent' : 'myapp/0.0.1'}
"""赋值时必须同步变量名才能覆盖原有值"""
r = requests.get(self.url, headers=headers, params=payload)
r.encoding = 'utf-8'
print(r.text)
def Control():
“”“这个作为class的控制器“”“
#url = "http://www.mifan.com.tw"
#url = "http://www.baidu.com"
#url = "http://www.github.com"
url = "http://www.njfhyey.com/new_vw.php"
site = website(url)
#site._getHead()
#site._reWirte()
site._setVariable()
Control()