【问题标题】:Scrapy, Parse items from 1st page then a follow link to get additional itemsScrapy,从第一页解析项目,然后点击链接以获取其他项目
【发布时间】:2016-02-03 01:03:26
【问题描述】:

更新:我能够让它移动,但它不会返回子页面并再次迭代序列。 我试图提取的数据在这样的表中:

表 日期_1 |来源_1 |链接到文章_1 | 日期_2 |来源_2 |链接到文章_2 | 等等……

我需要先收集date_1,source_1,然后进入文章的链接并重复......

任何帮助将不胜感激。 :)

from scrapy.spiders import BaseSpider, Rule
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors import LinkExtractor
from dirbot.items import WebsiteLoader
from scrapy.http import Request
from scrapy.http import HtmlResponse



class DindexSpider(BaseSpider):
name = "dindex"
allowed_domains = ["newslookup.com"]
start_urls = [
      "http://www.newslookup.com/Business/"
]

def parse_subpage(self, response):
    self.log("Scraping: " + response.url)
    il = response.meta['il']
    time = response.xpath('//div[@id="update_data"]//td[@class="stime3"]//text()').extract()
    il.add_value('publish_date', time)
    yield il.load_item()


def parse(self, response):
    self.log("Scraping: " + response.url)
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//td[@class="article"]')

    for site in sites:
        il = WebsiteLoader(response=response, selector=site)
        il.add_xpath('name', 'a/text()')
        il.add_xpath('url', 'a/@href')
        yield Request("http://www.newslookup.com/Business/", meta={'il': il}, callback=self.parse_subpage)

【问题讨论】:

    标签: python callback scrapy scrapy-spider


    【解决方案1】:

    这只是因为您需要使用CrawlSpider class 而不是BaseSpider:

    from scrapy.spiders import CrawlSpider
    
    class DindexSpider(CrawlSpider):
        # ...
    

    【讨论】:

    • 我最终让蜘蛛运行,但现在它停止并出现此错误“ il.add_value('time', response['time']) TypeError: 'HtmlResponse' object has no attribute 'getitem' "
    • 有趣的是,我所做的只是将 parse_page 更改为解析并运行。我也不知道为什么。
    • 虽然蜘蛛程序启动了,但它仍然关闭,从一个页面中提取某些项目然后跟随与这些项目关联的链接的问题仍然没有运行。
    • 如果你使用 CrawlSpider(正如 alecxe 提到的),你不能自己定义 parse 函数,因为蜘蛛本身需要这个方法,它确保链接被爬取。您使用getitem 的错误消息是因为您使用response['ime'] 而不是response.meta['time']。
    猜你喜欢
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多