在模拟登陆上,requests确实比python标准库中的相关模块更加简洁.html
假设你须要去爬一组页面(targetUrls),而这些页面要登陆才能进行访问.那么requests可以提供一种至关简单的语法来实现.python
不过在此以前,你得先经过浏览器的开发人员工具肯定:json
1.递交用户名和密码的页面(loginUrl)浏览器
2.键值对(递交数据是以字典的形式)服务器
模拟举例:cookie
#肯定登陆页面地址和键值对 loginUrl = "http://..." loginData={ 'formhash' : "f474a8c6", 'cookietime' : 2592000, 'loginfield' : "username", 'username' : "...", 'password' : "...", 'userlogin' : "true",} s = requests.session() s.post(url=loginUrl,data=loginData) #定义目标页面的集合 targetUrls=["http://...","http://...",...] #依次处理这些目标页面 for x in targetUrls: r=s.get(x) #对r进行各类读取操做,例如r.content返回网站bytes数据,r.text返回网站Unicode数据.
注意,若是你要用中文正则匹配一个gb编码系的页面文本(r.text),那么你可能须要在匹配以前告诉requests,编码是gb系.即:session
for x in targetUrls: r=s.get(x)
r.encoding='gb18030'
不然,你的正则可能没法匹配到本应匹配到的中文字符.目前还不太了解为什么requests顽固的认为页面编码都是ISO-8859-1(西欧编码),即便它已经知道apparent_encoding的值为'GB2312'.app
.工具
requests把服务器返回的数据包装成一个对象,这个对象有不少有用的属性,咱们能够直接访问,很是方便.post
可算是没有浪费那么多时间去安装.来看看r都有些什么属性:
attrs=['apparent_encoding', 'close', 'connection', 'cookies', 'elapsed', 'encoding','headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'url'] for att in attrs: print (att,'->',getattr(r,att)) #text和content其实就是网站文本,太大了,单独列出来,只显示类型. print('type(r.text)','->',type(r.text)) print('type(r.content)','->',type(r.content))
结果:
>>> apparent_encoding -> GB2312 close -> <bound method Response.close of <Response [200]>> connection -> <requests.adapters.HTTPAdapter object at 0x01D5F4F0> cookies -> <<class 'requests.cookies.RequestsCookieJar'>[]> elapsed -> 0:00:00.758043 encoding -> ISO-8859-1 headers -> CaseInsensitiveDict({'x-powered-by': 'PHP/5.2.17', 'date': 'Sun, 24 Nov 2013 16:31:04 GMT', 'keep-alive': 'timeout=5, max=100', 'content-encoding': 'gzip', 'content-type': 'text/html', 'connection': 'Keep-Alive', 'server': 'LiteSpeed', 'vary': 'Accept-Encoding, Accept-Encoding', 'transfer-encoding': 'chunked'}) history -> [] iter_content -> <bound method Response.iter_content of <Response [200]>> iter_lines -> <bound method Response.iter_lines of <Response [200]>> json -> <bound method Response.json of <Response [200]>> links -> {} ok -> True raise_for_status -> <bound method Response.raise_for_status of <Response [200]>> raw -> <requests.packages.urllib3.response.HTTPResponse object at 0x02622750> reason -> OK request -> <PreparedRequest [GET]> status_code -> 200 url -> http://... type(r.text) -> <class 'str'> type(r.content) -> <class 'bytes'>
requests官方中文教程:
http://cn.python-requests.org/en/latest/user/quickstart.html