Python进阶之使用Scrapy实现自动登录Github的两种方法(POST,FormRequest,from_response)

1. 通过.FormRequest()实现登录github

  • 需求: 通过提交表单自动登录github
  • 需求分析:
    • 1.目标登录页面: https://github.com/login

    • 2.表单提交页面: https://github.com/session

    • 2.form表单数据:

      commit: Sign in
      authenticity_token: VS+fpLCrOk/5kzW21z4TvUgAhT3TWyork1NQAmZ4Dv7z4noiYDFxNJ3VD18SKskyPrcyGMeo3KADeGB2PSORPw==
      ga_id: 2106354846.1594901172
      login: xxxxx
      password: 123456
      webauthn-support: supported
      webauthn-iuvpaa-support: unsupported
      return_to:
      required_field_0ac1:
      timestamp: 1599141753983
      timestamp_secret: 3a2dd1bb343778097362c2440e688357aefc732642ccb354ba5a4da42889181e

    • 3 多次提交不同密码看看表单数据有哪些是变化的

    • 4.通过检查html发现authenticity_token,timestamp, timestamp_secret对应的数据

github1.py

import scrapy
from ps import k_login,k_password

class GloginSpider(scrapy.Spider):
    name = 'github1'
    allowed_domains = ['github.com']
    start_urls = ['https://github.com/login']
    url = 'https://github.com/session'
    # def start_requests(self):
    def parse(self, response):
        commit = 'Sign in'
        authenticity_token = response.xpath('//input[@name="authenticity_token"]/@value').extract_first()
        # .extract_first是在选择器列表中返回第一个列表值
        # 等同于.extract()[0],也可以是[0].extract()
        # 测试中发现ga_id在登录前为空,尝试不添加这一项
        # ga_id = response.xpath('//meta[@name="octolytics-dimension-ga_id"]/@content').extract()
        login = k_login
        password = k_password
        timestamp = response.xpath('//input[contains(@name,"timestamp")]/@value')[0].extract()
        timestamp_secret = response.xpath('//input[contains(@name,"timestamp")]/@value')[1].extract()
        # print(authenticity_token)
        # print(ga_id)
        # print(timestamp,timestamp_secret)

        # 定义一个字典提交数据
        form_data = {
            'commit': commit,
            'authenticity_token': authenticity_token,
            # 'ga_id': ga_id,
            'login': login,
            'password': password,
            'webauthn-support': 'supported',
            'webauthn-iuvpaa-support': 'unsupported',
            'timestamp': timestamp,
            'timestamp_secret': timestamp_secret,
        }

        # scrapy.Request只支持get请求
        # post请求可以使用.FormRequest,默认为POST
        yield scrapy.FormRequest(
            url=self.url,
            formdata=form_data,
            callback=self.after_login
        )

    def after_login(self,response):

        # print(response.body.decode('utf-8'))
        with open('./github.html','w',encoding='utf-8') as f:

            f.write(response.body.decode('utf-8'))

2. 通过.FormRequest.from_response()实现登录github

github2.py

import scrapy
from ps import k_login,k_password

class Gitlog2Spider(scrapy.Spider):
    name = 'github2'
    allowed_domains = ['github.com']
    start_urls = ['http://github.com/login']

    def parse(self, response):

        # 通过scrapy.FormRequest.from_response()提交数据
        # 源码中已有的数据不需要再进行提交
        # 可以用来实现快速登录
        yield scrapy.FormRequest.from_response(
            # 请求响应结果
            response=response,
            # 提交数据
            formdata={
                'login': k_login,
                'password': k_password
            },
            callback=self.after_login

        )

    def after_login(self,response):

        # print(response.body.decode('utf-8'))
        with open('./github2.html','w',encoding='utf-8') as f:

            f.write(response.body.decode('utf-8'))

ps.py

k_login = '你的用户名'
k_password = '你的密码'

3. 需要注意的几点:

  1. 方法一是通过构造POST表单的方法,在https://github.com/session进行数据提交的方式进行登录
  2. 方法二对于源码中存在的数据不需要重复提交,只提交源码中没有的,如用户名密码等
  3. 注意根源目录的设置,右键设置为根源目录,这样就可以直接引用项目中的其他py模块
    根源目录的设置
    4…extract_first是在选择器列表中返回第一个列表值。等同于.extract()[0],也可以是[0].extract()
    5.一定要仔细检查源码,浏览器检查中的element数据不一定源码中都有。测试中发现ga_id在登录前为空,尝试不添加这一项。
    6.formdata表单中的数据如果为空,可以不进行提交
    7.POST的内容一定为字典格式,上边的两种方法本质都是构造表单字典进行POST请求登录
    8.scrapy.Request只支持get请求,post请求可以使用.FormRequest,默认为POST,不需要专门设置
    9.通过response.body.decodew(‘utf-8’)可以查看response结果
    10.当…from_response()中没有callback参数时,可以硬写,通过self.函数名传递函数,不需要加括号
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
出现请求超时的原因可能有很多,比如网络原因、服务器响应速度慢等等。在使用Scrapy发送POST请求时,可以尝试以下几种方法来解决超时问题: 1. 增加超时时间:在Scrapy的settings.py文件中设置DOWNLOAD_TIMEOUT参数,增加请求超时时间,例如: ``` DOWNLOAD_TIMEOUT = 20 ``` 2. 使用RetryMiddleware:在Scrapy使用RetryMiddleware可以自动重试请求,可以设置重试次数和重试时间间隔。在settings.py文件中添加以下代码: ``` RETRY_TIMES = 3 RETRY_HTTP_CODES = [500, 502, 503, 504, 400, 403, 404, 408] DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, 'scrapy_proxies.RandomProxy': 100, 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110, } ``` 3. 使用代理:在Scrapy使用代理可以解决网络闪断等问题,可以使用scrapy_proxies库来实现代理功能。在settings.py文件中添加以下代码: ``` PROXY_LIST = '/path/to/proxy/list.txt' PROXY_MODE = 0 RANDOM_UA_PER_PROXY = True ``` 其中,PROXY_LIST为代理IP列表文件路径,PROXY_MODE为代理模式,0为随机选择代理IP,1为顺序选择代理IP。RANDOM_UA_PER_PROXY为是否在每个代理IP上使用随机User-Agent。 4. 使用requests库:如果使用Scrapy发送POST请求仍然存在超时问题,可以尝试使用requests库来发送请求。在Scrapy中可以使用scrapy-requests库来集成requests库,具体使用方法可以参考文档:https://github.com/scrapy-plugins/scrapy-requests
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

kingx3

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

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

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

打赏作者

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

抵扣说明:

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

余额充值