Python 3.3.3 使用requests模拟登录网站

时间:2021-12-21 16:16:55

在模拟登录上,requests确实比python标准库中的相关模块更加简洁.

假设你需要去爬一组页面(targetUrls),而这些页面要登录才能进行访问.那么requests能够提供一种相当简单的语法来实现.

不过在此之前,你得先通过浏览器的开发人员工具确定:

1.递交用户名和密码的页面(loginUrl)

2.键值对(递交数据是以字典的形式)

模拟举例:

#确定登录页面地址和键值对
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系.即:

for x in targetUrls:
r=s.get(x)
r.encoding='gb18030'

否则,你的正则可能无法匹配到本应匹配到的中文字符.目前还不太了解为何requests顽固的认为页面编码都是ISO-8859-1(西欧编码),即使它已经知道apparent_encoding的值为'GB2312'.

.

requests把服务器返回的数据包装成一个对象,这个对象有很多有用的属性,我们可以直接访问,非常方便.

可算是没有浪费那么多时间去安装.来看看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