美文网首页
【python2.7】使用requests模块登陆豆瓣

【python2.7】使用requests模块登陆豆瓣

作者: tonyemail_st | 来源:发表于2017-11-04 19:24 被阅读0次

不需要user-agent伪装就可以登陆成功,测试时间:2017-11-04

# -*- coding: utf-8 -*-
import requests
import re
from bs4 import BeautifulSoup

'''
新建一个Session实例,发送get请求,判断是否有captcha
'''

s = requests.Session()
url_login = 'https://accounts.douban.com/login'
response = s.get(url_login)
# print response.request.headers
soup = BeautifulSoup(response.text, 'html.parser')
captcha = soup.find('img', id='captcha_image')

if captcha:
    captcha_url = captcha['src']
    print captcha_url
    captcha_text = raw_input('Please input the captcha:')
    re_captcha_id = r'<input type="hidden" name="captcha-id" value="(.*?)"/'
    captcha_id = re.findall(re_captcha_id, response.text)

    form_data = {
        'redir': 'https://www.douban.com/people/48373115/',
        'form_email': '15861591989',
        'form_password': 'cloud523',
        'captcha-solution': captcha_text,
        'captcha-id': captcha_id,
        # 'login': u'登陆'
    }
    r = s.post(url_login, data=form_data)
    with open("test.html", 'w') as fh:
        fh.write(r.text.encode("utf-8"))
        fh.close
else:
    form_data = {
        'redir': 'https://www.douban.com/people/48373115/',
        'form_email': '15861591989',
        'form_password': 'cloud523',
    }
    r = s.post(url_login, data=form_data)
    with open("test.html", 'w') as fh:
        fh.write(r.text.encode("utf-8"))
        fh.close

相关文章

网友评论

      本文标题:【python2.7】使用requests模块登陆豆瓣

      本文链接:https://www.haomeiwen.com/subject/tdlqmxtx.html