如何抓取网站上给出的每个链接并使用scrapy收集所有文本

时间:2016-06-09 02:35:36

标签: scrapy scrapy-spider

我跟着链接

https://stackoverflow.com/questions/19254630/how-to-use-scrapy-to-crawl-all-items-in-a-website

但事情对我来说不起作用。

我正在尝试通过网络学习数据。我正在实施http://scrapy.readthedocs.io/en/latest/intro/examples.html

上的教程

并且能够抓取指定的链接 这是示例代码快照

from scrapy.spiders import Spider
from scrapy.selector import Selector

from dirbot.items import Website


class DmozSpider(Spider):
    name = "dmoz"
    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):
        """
        The lines below is a spider contract. For more info see:
        http://doc.scrapy.org/en/latest/topics/contracts.html

        @url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/
        @scrapes name
        """
        sel = Selector(response)
        sites = sel.xpath('//ul[@class="directory-url"]/li')
        items = []

        for site in sites:
            item = Website()
            item['name'] = site.xpath('a/text()').extract()
            item['url'] = site.xpath('a/@href').extract()
            item['description'] = site.xpath('text()').re('-\s[^\n]*\\r')
            items.append(item)

        return items
项目的

和代码捕捉是

 from scrapy.item import Item, Field


class Website(Item):

    name = Field()
    description = Field()
    url = Field() 

我可以使用scrapy crawl dmoz

运行抓取工具

但无法实现以下内容

1. All given link on website
2. Didn't get all text from all possible link 
3. Want to save them to a file 

有人可以指导我,我的代码需要做哪些更改才能实现我的目标?

1 个答案:

答案 0 :(得分:0)

  1. 网站上的所有指定链接

    回复中没有class="directory-url"。 您可以使用sites = sel.xpath('//a/@href')而不是网站从网站获取所有指定的链接。过滤所需的网址

    或者

    如果您可以从主域(http://www.dmoz.org/)开始,例如

    doc = html.fromstring(response.body) sites = doc.xpath('.//section[@id="category-section"]//aside')

    for site in sites:     item = StackDemoItem()     item['name'] = site.xpath('.//div/h2/a/text()')     item['url'] = site.xpath('.//div/h2/a/@href')

    您必须使用item['url']附加域名才能获得正确的网址。对于其他网页的url路径,请执行相同的操作。

  2. 没有从所有可能的链接中获取所有文字

    大多数链接都没有文字。所以你必须从url本身剥离内容.else text = sel.xpath('//a/text()')

  3. 想要将它们保存到文件中

    您可以使用scrapy crawl your_crawler_name -o out.csv简单地保存内容,使用json或txt代替csv来处理这种文件。

相关问题