Skip to content

Simulated Login

Simulated login means using a crawler to programmatically perform the login operation on a website. Some platforms restrict their internal pages to authenticated users only, making login simulation a prerequisite before scraping protected content. The main challenge is handling CAPTCHAs.

Case Study: Scraping Resume Templates from Zhanzhang Sucai

# URL: https://sc.chinaz.com/jianli/free.html

import requests
from lxml import etree

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
}

import os
import time
if not os.path.exists('jlrar'):
    os.mkdir('jlrar')
frist_url = 'https://sc.chinaz.com/jianli/free.html'
base_url = 'https://sc.chinaz.com/jianli/free_%d.html'
for i in range(1, 5):
    if i == 1:
        new_url = frist_url
    else:
        new_url = format(base_url % i)
    html_data = requests.get(url=new_url, headers=headers).text
    tree = etree.HTML(html_data)
    url_list = tree.xpath('//div[@id="container"]/div/a/@href')
    for url in url_list:
        new_url = 'https:' + url
        response = requests.get(new_url)
        response.encoding = 'utf-8'
        data = response.text
        tree1 = etree.HTML(data)
        down_url = tree1.xpath('//div[@id="down"]//li/a/@href')[0]
        time.sleep(2)
        file_name = tree1.xpath('//div[@class="ppt_tit clearfix"]//h1/text()')[0]
        print(down_url, 'downloading')
        jl_data = requests.get(down_url).content
        with open('./jlrar/' + file_name + '.rar', 'wb') as fp:
            fp.write(jl_data)

Case Study: Scraping Financial News from Eastmoney

# URL: https://kuaixun.eastmoney.com/
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
}

url = 'https://newsapi.eastmoney.com/kuaixun/v1/getlist_102_ajaxResult_50_%d_.html?'
file_name = 'zx.txt'
fp = open(file_name, 'w', encoding='utf-8')
for i in range(1, 5):
    new_url = format(url % i)
    data = requests.get(new_url, headers=headers)
    data = json.loads(data.text.strip('var ajaxResult='))
    for i in data['LivesList']:
        print(i['title'], i['digest'])
        fp.write(i['title'] + ':' + i['digest'] + '\n')

Simulated Login Overview

  • What is simulated login? Using a crawler to perform the login operation automatically.
  • Why is it needed? Some platforms only expose their inner pages to logged-in users.
  • How to implement it? Replay the POST request that the login button triggers. The main obstacle is CAPTCHA solving.

CAPTCHA Solving

Use an online CAPTCHA-solving service to handle various CAPTCHA types (excluding slider CAPTCHAs, which require separate handling).

Popular services:

# Chaojiying client

#!/usr/bin/env python
# coding:utf-8

import requests
from hashlib import md5

class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: image bytes
        codetype: CAPTCHA type, see http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id: image ID of an incorrectly solved CAPTCHA
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()


# Helper function to solve a CAPTCHA image
def getCode_text(imgPath, imgType):
    chaojiying = Chaojiying_Client('227851369', '123456', '	911685')
                                   # username      password   software ID
    im = open(imgPath, 'rb').read()
    return chaojiying.PostPic(im, imgType)['pic_str']


# Solve a CAPTCHA
getCode_text('chaojiying_Python/a.jpg', 1004)

Case Study: Simulated Login on Gushiwen (Chinese Poetry Site)

import requests
from lxml import etree

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}

# Step 1: Fetch the login page and get the CAPTCHA image URL
main_url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
page_text = requests.get(url=main_url, headers=headers).text
tree = etree.HTML(page_text)
img_src = "https://so.gushiwen.cn" + tree.xpath('//*[@id="imgCode"]/@src')[0]
img_data = requests.get(img_src, headers=headers).content
with open('./code.jpg', 'wb') as fp:
    fp.write(img_data)
# Step 2: Solve the CAPTCHA
code_text = getCode_text('./code.jpg', 1004)
print(code_text)

Handling Dynamically Changing Request Parameters

Some login forms include hidden fields with values that change on every page load (e.g., ASP.NET __VIEWSTATE). Use one of these strategies to obtain them:

  • Search for them globally using a packet-capture tool (Fiddler / Charles)
  • Look for them in the HTML source of the login page (they are often hidden <input> elements)
# Use a Session so that cookies set during the GET carry over to the POST
sess = requests.Session()
main_url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
page_text = sess.get(url=main_url, headers=headers).text
tree = etree.HTML(page_text)
img_src = "https://so.gushiwen.cn" + tree.xpath('//*[@id="imgCode"]/@src')[0]
img_data = sess.get(img_src, headers=headers).content
with open('./code.jpg', 'wb') as fp:
    fp.write(img_data)
# Solve the CAPTCHA
code_text = getCode_text('./code.jpg', 1004)
print(code_text)

# Extract the dynamic hidden parameters from the page
__VIEWSTATE = tree.xpath('//*[@id="__VIEWSTATE"]/@value')[0]
__VIEWSTATEGENERATOR = tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value')[0]

# Submit the login form
login_url = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
data = {
    '__VIEWSTATE': __VIEWSTATE,
    '__VIEWSTATEGENERATOR': __VIEWSTATEGENERATOR,
    'from': 'http://so.gushiwen.cn/user/collect.aspx',
    'email': '15027900535',
    'pwd': 'bobo@15027900535',
    'code': code_text,
    'denglu': 'Login',
}

# Save the returned page locally to verify login success
login_page_text = sess.post(login_url, headers=headers, data=data).text
with open('./gushiwen.html', 'w', encoding='utf-8') as fp:
    fp.write(login_page_text)
Last updated on