进入豆瓣登陆页面:
从中可以获悉post操作时候对应的url为https://accounts.douban.com/login
F12上述页面,填入豆瓣的账号密码(仅仅是为了post一定的数据,所以,随意的账号和密码是可以的)。查看网络的数据变化:
从上图的Headers中可以看出,需要的表单项为下述四项:
redir: https://www.douban.com/
form_email:你的账号
form_password:你的密码
login:登录
当需要验证码的时候,则需要用到BeautifulSoup模块,完整的代码如下:
# -*- coding: utf-8 -*-
__author__ = 'jason'
import requests
import html5lib
import re
from bs4 import BeautifulSoup
s = requests.Session()
url_login = 'https://accounts.douban.com/login'
formdata = {
'redir': 'https://www.douban.com',
'form_email': 账号,
'form_password': 密码,
'login': u'登陆'
}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
r = s.post(url_login, data = formdata, headers = headers)
content = r.text
soup = BeautifulSoup(content, 'html.parser')
captcha = soup.find('img', id = 'captcha_image')#当登陆需要验证码的时候
if captcha:
captcha_url = captcha['src']
re_captcha_id = r'
captcha_id = re.findall(re_captcha_id, content)
print(captcha_id)
print(captcha_url)
captcha_text = input('Please input the captcha:')
formdata['captcha-solution'] = captcha_text
formdata['captcha-id'] = captcha_id
r = s.post(url_login, data = formdata, headers = headers)
with open('contacts.txt', 'w+', encoding = 'utf-8') as f:
f.write(r.text)
该方式则是利用上一次的登陆信息的cookie,在下一次登陆的时候,直接登陆。那么,需要先将第一次登陆时候的cookie保留。下述代码假设已经保留的对应的cookie信息:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'}
cookies = {cookie信息}
url = 'http://www.douban.com'
r = requests.get(url, cookies = cookies, headers = headers)
with open('douban_2.txt', 'wb+') as f:
f.write(r.content)