python scrapy框架

2023-05-12438

Scrapy 是一个用于抓取网站和提取结构化数据的应用程序框架,可 用于各种有用的应用程序,如数据挖掘、信息处理或历史存档。 尽管 Scrapy 最初是为网络抓取而设计的,但它也可用于使用 API提取数据或用作通用网络爬虫。


Scrapy的优势


可以容易构建大规模的爬虫项目

内置re、xpath、css选择器

可以自动调整爬行速度

开源和免费的网络爬虫框架

可以快速导出数据文件: JSON,CSV和XML

可以自动方式从网页中提取数据(自己编写规则)

Scrapy很容易扩展,快速和功能强大

这是一个跨平台应用程序框架(在Windows,Linux,Mac OS)

Scrapy请求调度和异步处理


安装 


pip install scrapy


创建项目


scrapy startproject scrapy01(project_name)


文件目录




 文件说明




 创建爬虫


scrapy genspider 爬虫名 爬虫的地址


爬虫的地址就是网站域名


比如 scrapy genspider aaa  www.aaa.com


创建成功后会在spiders目录下创建一个 爬虫名.py 的文件


内容包括


name: 它定义了爬虫的名称

allowed_domains: 它包含了爬虫抓取的URL;

start-urls: 爬虫开始爬行的URL列表;

parse(): 这是提取并解析数据的方法;

import scrapy

class aaaSpider(scrapy.Spider):

name = "aaa"

allowed_domains = ["www.aaa.com"]

start_urls = ["https://aaa.com/article_category.php?id=1"]

def parse(self, response):

selector_list = response.xpath('//div[@class="announcements_list"]/a')

all_data = []

for selector in selector_list:

blog_dict = {}

blog_dict['img']= selector.xpath('./img/@src').extract_first()

blog_dict['title']= selector.xpath('./div[@class="information"]/h6/text()').extract_first()

blog_dict['time']=selector.xpath('./div[@class="information"]/span/text()').extract_first()

blog_dict['textms']=selector.xpath('./div[@class="information"]/p/text()').extract_first()

all_data.append(blog_dict)

return(all_data)

运行方法


scrapy crawl 爬虫名 


比如 scrapy crawl aaa


这里可以加参数生成到指定的文件


scrapy crawl aaa -o aaa.json -t json


scrapy 内置主要有四种:JSON,JSON lines,CSV,XML 最常用的导出结果格为JSON