一、背景环境
- 环境介绍
操作系统:Win10
Python版本:Python3.6
Scrapy版本:Scrapy1.5.1
本篇主要目的是在wei.py文件使用scrapy.FormRequest来进行登录演示,主要说明都写在代码注释内。
二、代码
-
项目目录结构
- wei.py文件
# -*- coding: utf-8 -*-
import scrapy
import json
class WeiSpider(scrapy.Spider):
name = 'wei'
allowed_domains = ['weibo.cn']
# start_urls = ['http://weibo.cn/']
# 当引擎把start_urls中的内容放入调度器中以后,会调取下载器发起get请求,现在如果需发送post请求,就需要把start_urls注视掉
# def parse(self, response):
# pass
# 重写一个方法
def start_requests(self):
# 这个方法当下载器开始发起请求之前被调用
# 在这个方法我们可以把下载器截获,改变其原来的请求方式
login_url = "https://passport.weibo.cn/sso/login" # post请求的接口url
# post提交的数据
data = {
'username': 'USERNAME',
'password': 'PASSWORD',
'savestate': '1',
'r': 'https://weibo.cn/?luicode=20000174',
'ec': '0',
'pagerefer': 'https://weibo.cn/pub/?vt=',
'entry': 'mweibo',
'wentry': '',
'loginfrom': '',
'client_id': '',
'code': '',
'qq': '',
'mainpageflag': '1',
'hff': '',
'hfp': ''
}
yield scrapy.FormRequest(url=login_url,formdata=data,callback=self.parse_login)
def parse_login(self, response):
# print(response.text)
# 判断登录是否成功
if json.loads(response.text)["retcode"] == 20000000:
print("登录成功!")
# 访问主页
main_url = "https://weibo.cn/?since_id=0&max_id=H0moBsJrC&prev_page=1&page=1"
yield scrapy.Request(url=main_url,callback=self.parse_info)
else:
print("登录失败!")
def parse_info(self, response):
print(response.text)
""" 在这里解析
xxxxxxxxx
"""
- settings.py
# -*- coding: utf-8 -*-
# Scrapy settings for Weibo project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'Weibo'
SPIDER_MODULES = ['Weibo.spiders']
NEWSPIDER_MODULE = 'Weibo.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 2
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
# COOKIES_ENABLED = False
# 在scrapy中会话处理默认是开启的,在这里可以关闭
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Content-Type': 'application/x-www-form-urlencoded',
'Connection': 'keep-alive',
# 'Host': 'passport.weibo.cn', # 这个主机名必须注释掉,当请求头中主机名指定为某个值的时候,后面每一次发起请求都会把url的主机名重定向该主机名下面
'Origin': 'https://passport.weibo.cn',
'Referer': 'https://passport.weibo.cn/signin/login?entry=mweibo&r=https%3A%2F%2Fweibo.cn%2F%3Fluicode%3D20000174&backTitle=%CE%A2%B2%A9&vt='
}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'Weibo.middlewares.WeiboSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'Weibo.middlewares.WeiboDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'Weibo.pipelines.WeiboPipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
settings文件我们主要对请求头进行一些设置。登录成功后scrapy是默认保存cookies的,如果不需要保存可以在settings文件里进行配置。
微博会对一个太过频繁访问的用户进行冻结,而这时,我们可以使用很多个账户进行登录,再将登录后的Cookies保存到Cookies池(推介使用Redis数据库来存储我们的Cookie池)并进行存储并定时检测,抛出检测后过期或不可用的Cookies。