10、利用requests获取数据1

python requests

在开始之前,先对本次内容做如下规划:
第一部分:介绍爬虫的伪装
第二部分:介绍常见页面爬取方式

...
其他,更加高深的内容,在后期学习中持续更新

第一部分:爬虫的伪装

爬虫伪装的最高境界就是一个搜索引擎,至少本人是这样的认为的。

  • 伪装代码
  • 利用无界面浏览器,selenium

本次主要介绍伪装代码

伪装代码

伪装user-agent

1、利用F12 去网页复制,这是最常用,最方便的一种方式(请自行尝试,要是不会的话,请留言。)
2、利用fake 包将随机生成一个 user-agent
参考官网
fake-useragent
举栗如下:

from fake_useragent import UserAgent
ua = UserAgent()
ua.ie   # 获得一个ie的user_agent,下面同理
ua.chrome
ua.opera
ua.google
ua.firefox
ua.ff
ua.safari
...

每次调用,返回的都是随机user_agent

for i in range(10):
      print(ua.ie)

# 结果如下:
"""
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; Media Center PC 6.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C)
Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)
Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0;  rv:11.0) like Gecko
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; FunWebProducts)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; SLCC1; .NET CLR 1.1.4322)

"""

伪装cookie

1、 从页面获取想要网页的cookie,这个需要手动查找
2、 利用requests中的session,个人比较懒,所有首选session 。 requests文档

import requests
s = requests.Session()  # 创建session实例
s.get("登录网址")  # 登录网址的cookie以及其他的东西保存在s对象中
response = s.get("真实数据网址")   # 利用s对象发起请求,获取数据

其中s = requests.Session() 这是一个对象,我们利用这个对象来进行,进一步的探索
回顾一下:一个对象主要有两部分组成,属性和方法

  • 属性:多为静态的数据,名称多为名词
  • 方法:为处理方式(函数),名称多为动词
improt requests
s = requests.Session()
print(dir(s))
'''
['__attrs__', '__class__', '__delattr__', '__dict__', 
'__dir__', '__doc__', '__enter__', '__eq__', '__exit__', 
'__format__', '__ge__', '__getattribute__', '__getstate__', 
'__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', 
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__setstate__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 
'adapters', 'auth', 'cert', 'close', 'cookies', 'delete', 
'get', 'get_adapter', 'get_redirect_target', 'head', 'headers', 
'hooks', 'max_redirects', 'merge_environment_settings', 'mount', 
'options', 'params', 'patch', 'post', 'prepare_request', 'proxies', 
'put', 'rebuild_auth', 'rebuild_method', 'rebuild_proxies', 'request', 
'resolve_redirects', 'send', 'stream', 'trust_env', 'verify']
上述部分为s对象的属性和方法,略过其中不认识的。
重点关注一下几个
'close', 'cookies', 'delete','get',  'headers','params','post','proxies', 'put','verify'
'''
# 若还是不懂,请参考官方手册,或者 help(s.xxx)

第二部分:介绍常见页面爬取方式

get , post , put , delete
最常用,get,post

# requests.get 可以添加的参数有多少
'''
url -- URL for the new Request object.
params -- (optional) Dictionary(字典) or bytes to be sent in the query string for the Request.  关键参数  kw=pyhton
data -- (optional) Dictionary(字典) or list of tuples [(key, value)] (will be form-encoded), bytes, or file-like object to send in the body of the Request.  提交数据
json -- (optional) json data to send in the body of the Request.
headers -- (optional) Dictionary(字典) of HTTP Headers to send with the Request.  
cookies -- (optional) Dict(字典) or CookieJar object to send with the Request.  
files -- (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.
auth -- (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
timeout (float(浮点数) or tuple) -- (optional) How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple. 超时,等待时间
allow_redirects (bool) -- (optional) Boolean(布尔值). Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True. 是否允许重定向
proxies -- (optional) Dictionary(字典) mapping protocol to the URL of the proxy.  设置代理
verify -- (optional) Either a boolean(布尔值), in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True.  SSL验证
stream -- (optional) if False, the response content will be immediately downloaded.
cert -- (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
'''

requests.post,同上...

headers里面我们可以放什么数据

headers = {
      "Accept" : # 用来表示浏览器支持的内容有那些
      "Accept-Encoding" : # 支持的压缩格式
      "Accept-Language" : # 支持的语言类型
      "User-Agent" : # 用户代理
      "Connection" : # 客户端与服务器的连接类型
      "Host" : # 请求的服务器网址
      "Referer" : # 来源网址地址
      ...
}

总结

利用requests库伪装一个爬虫还是非常简单的,只需要传递参数就可以完成一个简单爬虫的伪装
传递的参数如下:

  • headers
    - user-agent (必传)
  • cookie (可选)
  • timeout (可选)
  • proxies (可选)设置ip代理
  • verify (可选)设置SSL验证
原文地址:https://www.cnblogs.com/hefany/p/14229252.html