让我了解我想要实现的目标;我正在尝试为我的网站构建一个文章抓取工具,我想要迭代所有网页上的链接,提取元数据以确定它是否是一篇文章,如果是,则将该 URL + 相关数据存储在数据库(Mongo)。
我找到了 python-goose article extractor我想用它来检索完整的文章。但我认为我在这方面有些超前了。
下面的代码是我的尝试,它有效,但不迭代。我认为我需要一个 for 循环,但我不知道如何去做。有人能指出我正确的方向吗?
from scrapy import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from scrapy.linkextractors import LinkExtractor
from harland.items import *
class StuffSpider(Spider):
name = "stuff"
allowed_domains = ["stuff.co.nz"]
start_urls = [
"http://www.stuff.co.nz/business/industries/70284251/brazil-a-surprise-growth-market-for-moa"
]
rules = (Rule(sle(allow=["/business/"]), callback='parse_item', follow=True)
def parse(self, response):
article = Selector(response)
page = Selector(response).xpath('/html/head/meta[9]')
page_type = page.xpath('//meta[@property="og:type"]/@content').extract()
if "article" in page_type:
item = StuffItem()
item['url'] = page.xpath('//meta[@property="og:url"]/@content')
item['title'] = page.xpath('//meta[@property="og:title"]/@content')
item['description'] = page.xpath('//meta[@property="og:description"]/@content')
yield item
yield Request(item['url'], callback=self.parse)
最佳答案
如果您不使用循环或任何规则
,您的代码将不会迭代。
由于您的 example.com
域,很难判断如何最好地浏览这些文章(目前我不会将 Goose 纳入答案)。
您可以设置一个规则
来提取并跟踪网站上的 URL。您可以使用此方法遍历站点并访问所有 URL(您也可以定义限制)并执行特定的爬行行为。请参阅the docs了解更多信息。
第二种方法是自己提取 URL,并将其yield
作为新的Request
,让 Scrapy 知道要访问哪个站点。这会产生更多的编码开销,但网络流量更少,因为您可以告诉要加载哪些站点。要了解有关 Request
的更多信息,请参阅 the docs .
如果您从正在解析的站点中提取 URL 或子树列表,请使用循环(大多数情况下 for
就可以了)来进行迭代。
根据评论和编辑进行更新
您的提取无法在 parse
方法中工作,因为您尝试将 Selector
对象设置为 Field
值,然后使用这样的一个 选择器
作为请求
的URL。您应该从这些选择器中提取
内容。
您的规则
定义了callback='parse_item'
。目前我没有看到 parse_item
函数的实现。因此,即使规则
命中,由于缺少回调
,您也不会得到任何结果。
因此,要解决 parse
函数的问题,请使用以下内容填充您的 item
:
item['url'] = page.xpath('//meta[@property="og:url"]/@content').extract()[0]
item['title'] = page.xpath('//meta[@property="og:title"]/@content').extract()
item['description'] = page.xpath('//meta[@property="og:description"]/@content').extract()
这应该使您的 Request
能够启动并再次调用 parse
方法 - 这会导致一些重复,Scrapy 会用 告诉您>调试
消息。
关于python - 如何迭代网站scrapy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625874/