使用Scrapy抓取网站步骤:
- 创建一个Scrapy项目;
- 定义Item容器;
- 编写爬虫;
- 存储内容。
步骤详解
1.在 cmd 中输入scrapy startproject projectname 创建Scrapy项目。
2.Item是保存爬取到的数据的容器,使用方法类似python字典,并提供额外保护机制来避免拼写错误导致的未定义字段错误。
class DmozItem(scrapy.Item): # 定义要存储字段的格式
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field() #字段名 = 占位符
link = scrapy.Field()
desc = scrapy.Field()
3.编写爬虫类Spider,Spider是用户编写用于从网站上爬取数据的类 。 【本例子中包含了用于下载的初始URL,然后是如何跟进网页中的链接以及如何分析页面中的内容,还有提取生成item的方法。】
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz" # 唯一 用于确认蜘蛛的名字
allowed_domains = ['dmoztools.net'] # 确定爬取的范围 防止蜘蛛通过链接爬到其他地方无限递归下去
start_urls = [ # 开始爬取的网址
'http://www.dmoztools.net/Computers/Programming/Languages/Python/Books/',
'http://www.dmoztools.net/Computers/Programming/Languages/Python/Resources/'
]
def parse(self, response): # 用于处理来自Downloader的Responses,然后对他进行分析处理,并且提取给item
sites = response.xpath('//div[@class="title-and-desc"]')
items = [] # 存放需要提取的标题、连接、描述
for site in sites:
item = DmozItem()
item['title'] = site.xpath('a/div[@class="site-title"]/text()').extract()
item['link'] = site.xpath('a/@href').extract()
item['desc'] = site.xpath('div[@class="site-descr "]/text()').extract()
items.append(item)
return items
4.Scrapy它有自己的机制对于提取数据,我们叫它选择器。在Scrapy中使用一种基于XPath和CSS的表达式机制:Scrapy Selectors 。
- xpath():传入xpath表达式,返回该表达式所对应的所有节点的select list列表。
- css():传入CSS表达式,返回该表达式所对应的所有节点的select list列表 。
- extract():序列化该结点的unicode字符并返回list 。
- re():根据传入的正则表达式对数据进行提取,返回unicode字符串list列表。
XPath是一门在网页中查找特定信息的语言。所以用XPath来筛选数据,要比使用正则表达式容易些。
使用XPath时,可以先在cmd里对XPath表达式进行测试:
scrapy shell "网址"
scrapy crawl dmoz # 运行爬虫
scrapy crawl dmoz -o items.json -t json #将数据保存为json格式