scrapy(三)Requests/Response/日志处理/模拟登陆

1、Requests

1.1、自动去重

class ExampleSpider(scrapy.Spider):
    name = 'example'

    # 表示域名范围
    allowed_domains = ['baidu.com',]

    # 初始化域名不会考虑范围
    start_urls = ['https://www.taobao.com']

    def parse(self, response):
        print(response, '=======================')

        # 再次请求
        yield scrapy.Request(url='https://www.baidu.com', callback=self.parse)

自动去重 根据url的哈希值去重,判断是否重复
url哈希值保存在
参数

1.2、源码

class Request(object_ref):

    def __init__(self, url, callback=None, method='GET', headers=None, body=None,
                 cookies=None, meta=None, encoding='utf-8', priority=0,
                 dont_filter=False, errback=None, flags=None, cb_kwargs=None):

  • meta 用于在不同请求之间传递数据
  • dont_filter=False 自动去重参数,默认去重
  • errback=None 请求出现错误,回调方法
  • priority=0 优先级

其他

 Scrapy.http.Request类是scrapy框架中request的基类。它的参数如下:
url(字符串) - 此请求的URL
callback(callable)- 回调函数
method(string) - 此请求的HTTP方法。默认为'GET'。
meta(dict) - Request.meta属性的初始值。
body(str 或unicode) - 请求体。如果没有传参,默认为空字符串。
headers(dict) - 此请求的请求头。
cookies - 请求cookie。
encoding(字符串) - 此请求的编码(默认为'utf-8')此编码将用于对URL进行百分比编码并将body转换为str(如果给定unicode)。
priority(int) - 此请求的优先级(默认为0)。
dont_filter(boolean) - 表示调度程序不应过滤此请求。
errback(callable) - 在处理请求时引发任何异常时将调用的函数。
flags(list) - 发送给请求的标志,可用于日志记录或类似目的。
 ## 发送POST请求 scrapy.FormRequest()
 url + formdata

2、Response

用于手动构造response下载器
scrapy.http.response.Response()
scrapy.http.HtmlResponse()

class Response(object_ref):

    def __init__(self, url, status=200, headers=None, body=b'', flags=None, request=None):
        self.headers = Headers(headers or {})
        self.status = int(status)
        self._set_body(body)
        self._set_url(url)
        self.request = request
        self.flags = [] if flags is None else list(flags)
参数
url(字符串) - 此响应的URL
status(整数) - 响应的HTTP状态。默认为200。
headers(dict) - 此响应的响应头。dict值可以是字符串(对于单值标头)或列表(对于多值标头)。
body(字节) - 响应主体。要将解码后的文本作为str(Python 2中的unicode)访问,您可以使用response.text来自编码感知的 Response子类,例如TextResponse。
flags(列表) - 是包含Response.flags属性初始值的列表 。如果给定,列表将被浅层复制。
request(Requestobject) - Response.request属性的初始值。这表示Request生成此响应的内容。

3、日志处理

配置settings文件

# LOG_FILE = 'baidu.log'	# 将日志抛出至文件
LOG_LEVEL = 'ERROR'
class ExampleSpider(scrapy.Spider):
    name = 'example'

    # 表示域名范围
    allowed_domains = ['baidu.com',]

    # 初始化域名不会考虑范围
    start_urls = ['https://www.taobao.com']

    page = 1

    def parse(self, response):
        print(response, '=======================')
        if self.page > 10:
            raise IndexError

        # 再次请求
        yield scrapy.Request(url='https://www.baidu.com', callback=self.parse, dont_filter=True)
        self.page += 1

4、模拟登陆GitHub

找发送post请求的url

分析提交的参数 构造data数据包

1、找固定的参数
2、找变化的参数出现的位置
在这里插入图片描述

import scrapy
import time
from .password import password

class GithubLoginSpider(scrapy.Spider):
    name = 'github_login'
    # allowed_domains = ['dddd']
    start_urls = ['https://github.com/login']

    def parse(self, response):
        """
        解析token值,构造data,发送post请求
        :param response:
        :return:
        """
        authenticity_token = response.xpath('//input[@name="authenticity_token"]/@value').extract_first()
        timestamp = response.xpath('//input[@name="timestamp"]/@value').extract_first()
        formdata = {
            'authenticity_token': authenticity_token,
            'commit': 'Sign in',
            'ga_id': '1253089579.1572247309',
            'login': 'supercll',
            'password': password,
            'required_field_e400': '',
            'timestamp': str(int(time.time())*1000),
            'timestamp_secret': timestamp,
            'utf8': 'v',
            'webauthn-iuvpaa-support': 'unsupported',
            'webauthn-support': 'supported',
        }

        yield scrapy.FormRequest(url='https://github.com/session', formdata=formdata, callback=self.login_alter)

    def login_alter(self, response):
        if 'supercll' in response.text:
            print("登陆成功")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值