博客: https://www.cnblogs.com/bobo-zhang/p/10561617.html
pip install wheel
下载 Twisted-18.9.0-cp36-cp36m-win_amd64.whl
安装 twisted
pip install Twisted-18.9.0-cp36-cp36m-win_amd64.whl
pip install pywin32
pip install scrapy
ROBOTSTXT_OBEY = True #----------- 是否遵守robots.txt
CONCURRENT_REQUESTS = 16 ## ----------- 开启线程数量,默认16
AUTOTHROTTLE_START_DELAY = 3 # ----------- 开始下载时限速并延迟时间
AUTOTHROTTLE_MAX_DELAY = 60 # ----------- 高并发请求时最大延迟时间
# 最底下的几个:是否启用在本地缓存,如果开启会优先读取本地缓存,从而加快爬取速度,视情况而定
HTTPCACHE_ENABLED = True
HTTPCACHE_EXPIRATION_SECS = 0
HTTPCACHE_DIR = 'httpcache'
HTTPCACHE_IGNORE_HTTP_CODES = []
HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# 以上几个可以视项目需要开启,但是有两个参数最好每次都开启,而每次都是项目文件手动开启不免有些麻烦,最好是项目创建后就自动开启
# DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
# 这个是浏览器请求头,很多网站都会检查客户端的headers,比如豆瓣就是每一个请求都检查headers的user_agent,否则只会返回403,可以开启
#USER_AGENT = 'Chirco (+http://www.yourdomain.com)'
# 这个是至关重要的,大部分服务器在请求快了会首先检查User_Agent,而scrapy默认的浏览器头是scrapy1.1 我们需要开启并且修改成浏览器头,如:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1
# 解开注释
ITEM_PIPELINES = {
# 300 表示权重 越小优先级越高
'DemoPro.pipelines.DemoproPipeline': 300,
}
# 只打印 错误信息
LOG_LEVEL = 'ERROR'
LOG_FILE = 'log.txt'
spider -> 引擎 -> 调度器(去重,调度器) -> 引擎 -> 下载器 -> 网络 -> 下载器 -> 引擎 -> spider ->管道
class DemoSpider(scrapy.Spider):
name = 'demo' # 爬蟲文件的名称
# 允许的域名
# allowed_domains = ['www.xxx.com']
# 起始的 url 列表
start_urls = ['https://www.qiushibaike.com/text/']
# 请求成功的 回调函数 实现数据解析
def parse(self, response):
response.body # 获取二进制数据 同 requests 中的 content
response.text # 获取响应的 数据
response.xpath() # 直接使用 xpath 函数
# 只能取出一个 元素
author = div.xpath('./div/a[2]/h2/text()').extract_first()
# 返回的列表元素时一个 selector 对象
content = div.xpath('./a[1]//text()').extract()
基于终端指令的的 存储 scrapy crawl demo -o qiubai.csv
settings 配置
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# 解开注释
ITEM_PIPELINES = {
# 300 表示权重 越小优先级越高
'DemoPro.pipelines.DemoproPipeline': 300,
}
# 只打印 错误信息
LOG_LEVEL = 'ERROR'
在items.py 文件中
class DemoproItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# 对应要存储的 元素
author = scrapy.Field()
content = scrapy.Field()
pass
实现 爬虫文件中
import scrapy
from DemoPro.items import DemoproItem
class DemoSpider(scrapy.Spider):
def parse(self, response):
div_list = response.xpath('//div[@id="content-left"]/div')
for div in div_list:
author = div.xpath('./div/a[2]/h2/text()').extract_first()
content = div.xpath('./a[1]/div/span[1]//text()').extract()
content = ' '.join([i.strip() for i in content])
print(author, content)
item = DemoproItem()
# 并且将解析到的数据封装存储到了item类型的对象当中了
item['author'] = author
item['content'] = content
# 向管道提交item类型的对象
yield item
class DemoproPipeline(object):
fp = None
# 这个方法只执行一次
def open_spider(self, spider):
""" 父类的方法 开启文件句柄 """
self.fp = open('qiubai.txt', 'w', encoding='utf-8')
def process_item(self, item, spider):
author = item['author']
content = item['content']
self.fp.write(author + '\n' + content + '\n')
return item # 返回给了下一个即将被执行的管道类
def close_spider(self, spider):
self.fp.close()
settings 配置
ITEM_PIPELINES = {
'DemoPro.pipelines.DemoproPipeline': 300,
'DemoPro.pipelines.MySqlPipeline': 301,
'DemoPro.pipelines.RedisPipeline': 302,
# ... 注册其他的管道 类 300 为权重 权重小的 先执行
# 可注册使用 mysql redis mongodb .. 数据库
}
class MySqlPipeline(object):
conn = None
cursor = None
def open_spider(self, spider):
self.conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='', db='spider')
def process_item(self, item, spider):
self.cursor = self.conn.cursor()
try:
self.cursor.execute('insert into data(author, content) values(%s,%s)' % (item["author"], item["content"]))
self.conn.commit()
print(item['author'])
except Exception as e:
print(e, 11111111)
self.conn.rollback()
return item
def close_spider(self, spider):
self.cursor.close()
self.conn.close()
使用redis 存储
class RedisPipeline(object):
conn = None
def open(self, spider):
self.conn = redis.Redis(host='127.0.0.1', port=6379)
def process_item(self, item, spider):
data = {
'author': item['author'],
'content': item['content']
}
self.conn.lpush('qiubaiData', data)
Scrapy 框架 安装 五大核心组件 settings 配置 管道存储
原文:https://www.cnblogs.com/zhang-zi-yi/p/10749420.html