Scrapy模拟登录赶集网

3 篇文章 0 订阅
2 篇文章 0 订阅

在我们输错密码时按下F12就可查看到如下信息

 

会发现有个随机的hash值(普遍规律:这种hash值会在网页源码中)

于是我们去网页源码中找

 

 

在模拟登录赶集网的时候出现的问题:

1.allowed_domains这个字段的理解,回调函数失败的原因

(把限制域名注释掉就可以了!allowed_domains)

import scrapy
import re

class GanjiSpider(scrapy.Spider):
    name = 'ganji'
    allowed_domains = ['https://passport.ganji.com/login.php']
    start_urls = ['https://passport.ganji.com/login.php']

    def parse(self, response):
        #这个正则的意思就是打上括号就是只要括号内的东西
        hash_code=re.findall(r'"__hash__":"(.+)"',response.text)[0]
        yield scrapy.Request(img_url, callback=self.parse_info, meta={'hash_code':hash_code})
        #img_url=https://passport.ganji.com/ajax.php?dir=captcha&module=login_captcha&nocache=1583980633551

    #为什么出现了调用失败的情况?
    def parse_info(self,response):
        #传递过来的hash_code在requests中
        # hash_code=request.meta,request是在response中的
        hash_code=response.request.meta['hash_code']
        print(hash_code)
        with open('yzm.jpg','wb') as f:
            f.write(response.body)
        code=input("请输入验证码")

2.

#这个正则的意思就是打上括号就是只要括号内的东西

#函数之间传递参数用meta

#函数之间提交form用FormRequest

# -*- coding: utf-8 -*-
import scrapy
import re

class GanjiSpider(scrapy.Spider):
    name = 'ganji'
    #allowed_domains = ['https://passport.ganji.com/login.php']
    start_urls = ['https://passport.ganji.com/login.php']

    def parse(self, response):
        #这个正则的意思就是打上括号就是只要括号内的东西
        hash_code=re.findall(r'"__hash__":"(.+)"',response.text)[0]
        img_url=response.xpath("//*[@id='login-content']/div/div/div[1]/div[2]/form[1]/div[4]/label/img/@src").extract_first()
        img_url="https://passport.ganji.com/ajax.php?dir=captcha&module=login_captcha"
        #因为访问后才能得到验证码
        #函数之间传递参数用meta
        #callback后是函数名不是函数,这个已经错误几次了
        yield scrapy.Request(img_url, callback=self.parse_info, meta={'hash_code':hash_code})

    #为什么出现了调用失败的情况?
    def parse_info(self,response):
        #传递过来的hash_code在requests中
        # hash_code=request.meta,request是在response中的
        hash_code=response.request.meta['hash_code']
        print(hash_code)
        with open('yzm.jpg','wb') as f:
            f.write(response.body)
        code=input("请输入验证码")
        form_data={
                      'username': '',
                      'password': '',
                      'setcookie': '14',
                      'checkCode': code,
                      'next': '/',
                      'source': 'passport',
                      '__hash__': hash_code

        }
        login_url="https://passport.ganji.com/login.php"
        print(form_data)
        yield scrapy.FormRequest(login_url,callback=self.after_login, formdata=form_data)

    def after_login(self,response):
        print(response.text)

A:使用scrapy模拟登陆大众点评网的步骤如下: 1. 在settings.py中添加COOKIES_ENABLED=True,开启cookies支持; 2. 在spider中编写start_requests方法,发送GET请求到大众点评的登录页面,获取登录页面的cookie; 3. 编写parse方法,解析登录页面的源代码,提取出登录时需要的参数、加密token等信息; 4. 编写一个登录方法,使用加密token和传递用户名和密码设置POST请求,将用户凭证提交到登录页面; 5. 再次编写parse方法,使用selenium打开登录页面,成功登录后,提取响应页面的cookie; 6. 在后续的请求中使用该cookie,以保持用户的登录状态。 具体实现代码如下: ```python import scrapy from scrapy.http import FormRequest from selenium import webdriver class DianPing(scrapy.Spider): name = 'dianping' allowed_domains = ['www.dianping.com'] start_urls = ['https://account.dianping.com/login'] def start_requests(self): yield scrapy.Request(url=self.start_urls[0], callback=self.parse, meta={ 'splash': { 'endpoint': 'render.html', 'args': {'wait': 0.5}, }, 'selenium': True }) def parse(self, response): # 获取cookie cookie = response.headers.getlist('Set-Cookie') cookie = [c.decode('utf-8').split(';')[0] for c in cookie] cookie = '; '.join(cookie) # 获取加密token token = response.css('input[name="token"]::attr(value)').extract_first() # 提交登录请求 yield FormRequest.from_response(response, formdata={ 'account': 'your_username', 'password': 'your_password', 'token': token, 'redir': 'https://www.dianping.com', 'rememberMe': 'true', }, headers={ 'Cookie': cookie, }, callback=self.after_login, meta={ 'splash': { 'endpoint': 'render.html', 'args': {'wait': 0.5}, }, 'selenium': True }) def after_login(self, response): # 使用selenium打开登录页面,获取cookie if '登录' not in response.body.decode('utf-8'): driver = response.meta['driver'] driver.get(response.url) cookies = driver.get_cookies() cookie_dict = {} for cookie in cookies: cookie_dict[cookie['name']] = cookie['value'] yield scrapy.Request( url='https://www.dianping.com/', cookies=cookie_dict, callback=self.parse_homepage, meta={ 'splash': { 'endpoint': 'render.html', 'args': {'wait': 0.5}, } } ) def parse_homepage(self, response): print(response.body) ``` 上述代码中,我们通过在start_requests的meta中添加了splash和selenium参数,使得start_requests方法使用splash和selenium的渲染能力来处理请求。在parse方法中,我们获取了登录页面的cookie和加密token,并设置了POST请求,将用户凭证提交到登录页面。在after_login方法中,我们使用selenium打开登录页面,并在parse_homepage方法中解析响应页面的源代码。最后,在后续的请求中使用获取到的cookie即可保持用户的登录状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ATOM_123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值