开发手册 欢迎您!
软件开发者资料库

Scrapy - 提取项目

Scrapy提取项目 - 从简单和简单的步骤学习Scrapy,从基本到高级概念,包括概述,环境,命令行工具,蜘蛛,选择器,项目,项目装载程序,外壳,项目管道,Feed导出,请求和响应,链接提取器,设置,例外,创建项目,定义项目,第一个蜘蛛,爬行,提取项目,使用项目,以下链接,Scraped数据,日志记录,统计信息收集,发送电子邮件,Telnet控制台,Web服务。

描述

为了从网页中提取数据,Scrapy使用一种基于 XPath 和 CSS 表达式.以下是XPath表达式的一些示例 :

  • /html/head/title : 这将选择< title>元素,在< head>内HTML文档的元素.

  • /html/head/title/text() : 这将选择相同< title>内的文字.元素.

  • //td : 这将从< td>中选择所有元素.

  • //div [@class ="slice"] : 这将选择 div 中包含属性class ="slice"的所有元素

选择器有四个基本方法如下表所示 :

Sr.No方法&说明
1

extract()

它返回一个unicode字符串以及所选数据.

2

re()

它返回一个unicode字符串列表,当正则表达式作为参数给出时提取.

3

xpath()

它返回一个选择器列表,表示由作为参数给出的xpath表达式选择的节点.

4

css()

它返回一个选择器列表,它表示由作为参数给出的CSS表达式选择的节点.

使用Shell中的选择器

要演示具有内置Scrapy shell的选择器,您需要 IPython .重要的是,在运行Scrapy时,URL应该包含在引号内;否则带有"&"字符的网址将无效.您可以在项目的顶级目录中使用以下命令启动shell;减去;

scrapy shell "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/"

shell将如下所示 :

[ ... Scrapy log here ... ]2014-01-23 17:11:42-0400 [scrapy] DEBUG: Crawled (200) (referer: None)[s] Available Scrapy objects:[s]   crawler    [s]   item       {}[s]   request    [s]   response   <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>[s]   settings   [s]   spider     [s] Useful shortcuts:[s]   shelp()           Shell help (print this help)[s]   fetch(req_or_url) Fetch request (or URL) and update local objects[s]   view(response)    View response in a browserIn [1]:

当shell加载时,你可以分别使用 response.body response.header 访问正文或标题.同样,您可以使用 response.selector.xpath() response.selector.css()对响应运行查询.

例如 :

In [1]: response.xpath('//title')Out[1]: [My Book - Scrapy'>]In [2]: response.xpath('//title').extract()Out[2]: [u'My Book - Scrapy: Index: Chapters']In [3]: response.xpath('//title/text()')Out[3]: []In [4]: response.xpath('//title/text()').extract()Out[4]: [u'My Book - Scrapy: Index: Chapters']In [5]: response.xpath('//title/text()').re('(\w+):')Out[5]: [u'Scrapy', u'Index', u'Chapters']

提取数据

到我们从普通的HTML网站中提取数据ave检查站点的源代码以获取XPath.检查后,您可以看到数据将位于 ul 标记中.选择 li 标签中的元素.

以下代码行显示了不同类型数据的提取和减号;

用于选择li标签内的数据 :

response.xpath('//ul/li')

用于选择描述 :

response.xpath('//ul/li/text()' ).extract()

用于选择网站标题 :

response.xpath('//ul/li/a/text()').extract()

用于选择网站链接 :

response.xpath('//ul/li/a/@ href').extract()

以下代码演示了如何使用上面的提取器 :

import scrapyclass MyprojectSpider(scrapy.Spider):   name = "project"   allowed_domains = ["dmoz.org"]      start_urls = [      "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",      "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"   ]   def parse(self, response):      for sel in response.xpath('//ul/li'):         title = sel.xpath('a/text()').extract()         link = sel.xpath('a/@href').extract()         desc = sel.xpath('text()').extract()         print title, link, desc