首页 > 解决方案 > Scrapy 的网络图输出

问题描述

我对使用 Scrapy 很陌生,但遇到了困难。我正在尝试使用 scrapy 来抓取网站并返回节点和边列表,以构建从我的起始页到 x 深度的内部和外部网站的网络图(待定)。

我有以下代码,但我无法找出问题所在。

我的 items.py 文件如下所示:

from scrapy.item import Item, Field

class SitegraphItem(Item):
     url=Field()
     linkedurls=Field()

我的 graphspider.py 文件如下:

from scrapy.selector import HtmlXPathSelector
from scrapy.linkextractors import LinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.utils.url import urljoin_rfc
from sitegraph.items import SitegraphItem

class GraphspiderSpider(CrawlSpider):
    name = 'graphspider'
    allowed_domains = ['example.com']
    start_urls = ['https://www.example.com/products/']

    rules = (
        Rule(LinkExtractor(allow=r'/'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        hxs = HtmlXPathSelector(response)
        i = SitegraphItem()
        i['url'] = response.url
        i['http_status'] = response.status
        llinks=[]
        for anchor in hxs.select('//a[@href]'):
            href=anchor.select('@href').extract()[0]
            if not href.lower().startswith("javascript"):
                llinks.append(urljoin_rfc(response.url,href))
        i['linkedurls'] = llinks
        return i

我修改了 settings.py 文件以包括:

BOT_NAME = 'sitegraph'

SPIDER_MODULES = ['sitegraph.spiders']
NEWSPIDER_MODULE = 'sitegraph.spiders'
FEED_FORMAT="jsonlines"
FEED_URI="C:\\Users\Merrie\\Desktop\\testscrape\\sitegraph\\sitegraph.json"

当我运行它时,我正在使用以下代码:

$scrapy crawl graphspider -o attempt2.csv

我的输出表是空的。它还不断抛出此错误:“KeyError:'SitegraphItem 不支持字段:http_status'”

标签: pythonscrapy

解决方案


您的 items.py 中缺少http_status字段会导致错误,请更新它。

from scrapy.item import Item, Field

class SitegraphItem(Item):
    url=Field()
    linkedurls=Field()
    http_status=Field()

推荐阅读