10、scrapy1.3.0 中文教程

    xiaoxiao2021-03-25  120

      https://doc.scrapy.org/en/latest/intro/tutorial.html

      创建项目

      在开始爬取之前,您必须创建一个新的Scrapy项目。 进入您打算存储代码的目录中,运行下列命令:   

    scrapy startproject tutorial

      该命令将会创建包含下列内容的 tutorial 目录:   

    tutorial/ scrapy.cfg # 项目的配置文件 tutorial/ # 项目的python模块。之后您将在此加入代码。 __init__.py items.py # 项目中的item文件. pipelines.py # 项目中的pipelines文件. settings.py # 项目的设置文件. spiders/ # 放置spider代码的目录. __init__.py

      编写第一个爬虫(Spider)

      Spider是用户编写用于从单个网站(或者一些网站)爬取数据的类。

      其包含了一个用于下载的初始URL,如何跟进网页中的链接以及如何分析页面中的内容, 提取生成 item 的方法。      以下为我们的第一个Spider代码,保存在 tutorial/spiders 目录下的 quotes_spider.py 文件中:   

    import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" def start_requests(self): urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): page = response.url.split("/")[-2] filename = 'quotes-%s.html' % page with open(filename, 'wb') as f: f.write(response.body) self.log('Saved file %s' % filename)

      为了创建一个Spider,您必须继承 scrapy.Spider 类, 且定义以下三个属性:

      name: 用于区别Spider。 该名字必须是唯一的,您不可以为不同的Spider设定相同的名字。

      start_urls: 包含了Spider在启动时进行爬取的url列表。 因此,第一个被获取到的页面将是其中之一。 后续的URL则从初始的URL获取到的数据中提取。

      parse() 是spider的一个方法。 被调用时,每个初始URL完成下载后生成的 Response 对象将会作为唯一的参数传递给该函数。 该方法负责解析返回的数据(response data),提取数据(生成item)以及生成需要进一步处理的URL的 Request 对象。      爬取

      进入项目的根目录,执行下列命令启动spider:   

    scrapy crawl quotes

      crawl quotes 启动用于爬取 quotes.toscrape.com 的spider,您将得到类似的输出:   

    ... (omitted for brevity) 2016-12-16 21:24:05 [scrapy.core.engine] INFO: Spider opened 2016-12-16 21:24:05 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-12-16 21:24:05 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None) 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None) 2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/2/> (referer: None) 2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-1.html 2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-2.html 2016-12-16 21:24:05 [scrapy.core.engine] INFO: Closing spider (finished) ...

      现在,检查当前目录中的文件。你应该注意到了两个新的文件已被创建:quotes-1.html和quotes-2.html。就像我们 parse 方法指定的那样,有两个包含url所对应的内容的文件被创建了。

      刚才发生了什么?

      Scrapy为Spider的 start_urls 属性中的每个URL创建了 scrapy.Request 对象,并将 parse 方法作为回调函数(callback)赋值给了Request。

      Request对象经过调度,执行生成 scrapy.http.Response 对象并送回给spider parse() 方法。

      start_requests方法从结果集中获取数据

      为了方便start_requests()从scraps.Request的结果集urls取数据,你可以自定义URL结果集中创建start_url列表,spider在工作中通过start_requests()方法逐条从url列表中读取数据。

    import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] def parse(self, response): page = response.url.split("/")[-2] filename = 'quotes-%s.html' % page with open(filename, 'wb') as f: f.write(response.body)

      parse()方法来处理每个的URL请求,虽然我们没有明确告诉scrapy这样做。这是因为parse()是Scrapy的默认回调方法,这就是所谓的要求没有明确指定的回调。      在Shell中尝试Selector选择器

      为了介绍Selector的使用方法,接下来我们将要使用内置的 Scrapy shell 。Scrapy Shell需要您预装好IPython(一个扩展的Python终端)。

    scrapy shell 'http://quotes.toscrape.com/page/1/'

      当您在终端运行Scrapy时,请一定记得给url地址加上引号,否则包含参数的url(例如 & 字符)会导致Scrapy运行失败。

      shell的输出类似:   

    [ ... Scrapy log here ... ] 2016-09-19 12:09:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None) [s] Available Scrapy objects: [s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc) [s] crawler <scrapy.crawler.Crawler object at 0x7fa91d888c90> [s] item {} [s] request <GET http://quotes.toscrape.com/page/1/> [s] response <200 http://quotes.toscrape.com/page/1/> [s] settings <scrapy.settings.Settings object at 0x7fa91d888c10> [s] spider <DefaultSpider 'default' at 0x7fa91c8af990> [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 browser >>>

      当shell载入后,您将得到一个包含response数据的本地 response 变量。输入 response.body 将输出response的包体, 输出 response.headers 可以看到response的包头。

      更为重要的是,当输入 response.selector 时, 您将获取到一个可以用于查询返回数据的selector(选择器), 以及映射到 response.selector.xpath() 、 response.selector.css() 的 快捷方法(shortcut): response.xpath() 和 response.css() 。   

    >>> response.css('title') [<Selector xpath='descendant-or-self::title' data='<title>Quotes to Scrape</title>'>] >>> response.css('title::text').extract() ['Quotes to Scrape'] >>> response.css('title').extract() ['<title>Quotes to Scrape</title>'] >>> response.css('title::text').extract_first() 'Quotes to Scrape' >>> response.css('title::text')[0].extract() 'Quotes to Scrape' >>> response.css('title::text').re(r'Quotes.*') ['Quotes to Scrape'] >>> response.css('title::text').re(r'Q\w+') ['Quotes'] >>> response.css('title::text').re(r'(\w+) to (\w+)') ['Quotes', 'Scrape']

      您可以在终端中输入 response.body 来观察HTML源码并确定合适的XPath表达式。不过,这任务非常无聊且不易。您可以考虑使用Firefox的Firebug扩展来使得工作更为轻松。详情请参考 使用Firebug进行爬取 和 借助Firefox来爬取 。

      提取引用和作者

      现在你知道了一些关于选择和提取,让我们完成我们的蜘蛛代码,从网页中提取数据。

      在http://quotes.toscrape.com每个引用的HTML元素,像这样:   

    <div class="quote"> <span class="text">“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”</span> <span> by <small class="author">Albert Einstein</small> <a href="/author/Albert-Einstein">(about)</a> </span> <div class="tags"> Tags: <a class="tag" href="/tag/change/page/1/">change</a> <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a> <a class="tag" href="/tag/thinking/page/1/">thinking</a> <a class="tag" href="/tag/world/page/1/">world</a> </div> </div>

      让我们打开Scrapy shell尝试如何提取我们想要的数据:   

    $ scrapy shell 'http://quotes.toscrape.com'

      我们得到HTML元素选择器列表数据:   

    >>> response.css("div.quote")

      每个选择器的查询返回的上述允许我们运行进一步查询的子元素。让我们选择第一个变量,这样我们就可以运行我们的CSS选择器选择在一个特定的结果集:   

    >>> quote = response.css("div.quote")[0]

      现在,让我们从结果集中提取标题,作者和标签:   

    >>> title = quote.css("span.text::text").extract_first() >>> title '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”' >>> author = quote.css("small.author::text").extract_first() >>> author 'Albert Einstein' >>> tags = quote.css("div.tags a.tag::text").extract() >>> tags ['change', 'deep-thoughts', 'thinking', 'world']

      在想通了如何提取每一点数据,我们现在可以遍历所有元素的引用,把它们一起放入一个Python的字典:   

    >>> for quote in response.css("div.quote"): ... text = quote.css("span.text::text").extract_first() ... author = quote.css("small.author::text").extract_first() ... tags = quote.css("div.tags a.tag::text").extract() ... print(dict(text=text, author=author, tags=tags)) {'tags': ['change', 'deep-thoughts', 'thinking', 'world'], 'author': 'Albert Einstein', 'text': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'} {'tags': ['abilities', 'choices'], 'author': 'J.K. Rowling', 'text': '“It is our choices, Harry, that show what we truly are, far more than our abilities.”'} ... a few more of these, omitted for brevity >>>

      在爬虫中提取数据

      让我们回到我们的在爬虫中,直到现在,它不会提取任何特定的数据,只保存整个HTML文件到本地。让我们从上面的逻辑集成到我们的在爬虫代码中。

      一个Scrapy蜘蛛从页面中提取数据通常会产生许多字典。要做到这一点,我们使用yield回调,正如你看到下面:   

    import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').extract_first(), 'author': quote.css('small.author::text').extract_first(), 'tags': quote.css('div.tags a.tag::text').extract(), }

      如果运行此蜘蛛,它将输出提取的数据与日志:

    2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/> {'tags': ['life', 'love'], 'author': 'André Gide', 'text': '“It is better to be hated for what you are than to be loved for what you are not.”'} 2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/> {'tags': ['edison', 'failure', 'inspirational', 'paraphrased'], 'author': 'Thomas A. Edison', 'text': "“I have not failed. I've just found 10,000 ways that won't work.”"}

      保存爬取到的数据

      最简单存储爬取的数据的方式是使用 Feed exports:  

    scrapy crawl quotes -o quotes.json

      该命令将采用 JSON 格式对爬取的数据进行序列化,生成 quotes.json 文件。

      在类似本篇教程里这样小规模的项目中,这种存储方式已经足够。 如果需要对爬取到的item做更多更为复杂的操作,您可以编写 Item Pipeline 。 类似于我们在创建项目时对Item做的,用于您编写自己的 tutorial/pipelines.py 也被创建。 不过如果您仅仅想要保存item,您不需要实现任何的pipeline。

    转载请注明原文地址: https://ju.6miu.com/read-15964.html

    最新回复(0)