我尝试使用请求库用python登录到9gag。我用firebug检查了邮件包,发现使用了csrftoken。最后,我设法得到了csrftoken并用它发出了请求。在
但是当我发布登录参数时,我得到一个错误页面,上面写着“disablecookiestologin”。我使用请求会话来保存登录cookies。在
我的问题是,如果我不登录,我就无法获得nsfw帖子的链接。 我应该修改一下HTTP头吗?在
这是我的代码:
import requests
import os
import re
from collections import OrderedDict
class Ninegaginstance():
def __init__(self, username, password):
self.s = requests.Session()
self.s.headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
csrf = self.get_csrf(self.s.get('http://m.9gag.com/login').text)
payload = OrderedDict([('csrftoken', csrf), ('password', password),
('username', username)])
print(payload)
self.login(payload)
self.getpage()
def get_csrf(self, source):
match_csrf = re.compile('(name=\"csrftoken\" value=\")([\w\d]+)')
return match_csrf.search(source).group(2)
def login(self, credentials):
loginpage = self.s.post('http://m.9gag.com/login', params=credentials)
print(loginpage.status_code)
print(self.s.cookies)
with open('login.html', 'w') as loginpagefile:
print(loginpage.text, file=loginpagefile)
def getpage(self):
ninegagpage = self.s.get('http://m.9gag.com')
with open('9gagsource.html', 'w') as ninegagfile:
print(ninegagpage.text, file=ninegagfile)
newninegaginstance = Ninegaginstance('myusername', 'mypassword')
目前没有回答
相关问题 更多 >
编程相关推荐