scrapy 如何爬取不同的网页URL结构,返回相同的item

问题描述

例如有一个网站内的有三个板块都是公司的新闻相关
https://www.glprop.com.cn/pre...
https://www.glprop.com.cn/in-...
https://www.glprop.com.cn/in-...
这三个页面都有新闻标题,时间,URL,每个页面还有下一页的这种新闻链接。

问题出现的环境背景及自己尝试过哪些方法

我定义了一个item
class PuluosiNewsItem(scrapy.Item):

newstitle=scrapy.Field()
newtiems=scrapy.Field()
newslink=scrapy.Field()

然后spider里面想通过获取三个url构建request然后回调函数getnews来获取新闻事件,新闻标题,新闻链接,但是每个URL里面新闻又按年份进行了分类,类似于下一页下一页,实在不知道如何写spider从三个url里面返回相同的item,难道要写三个spider吗?
class PuluosiSpider(scrapy.Spider):

name = 'puluosi'
allowed_domains = ['glprop.com.cn']
start_urls = ['https://www.glprop.com.cn/press-releases.html']

#获取所有href
def parse(self, response):
    print('此时启动的爬虫为:puluosi' )
    urllist=response.xpath('//div[@class="menu"]/ul/li[4]//li')
    #把媒体中的国际市场发债信息url去除
    urllist.pop()
    base_url='https://www.glprop.com.cn'
    for web in urllist:
        url=base_url+web.xpath('.//a/@href').extract()[0]
        yield scrapy.Request(url,callback=self.getnews)
        # print("REQUEST:",scrapy.Request)

def getnews(self,response):
    pass
阅读 5.7k
2 个回答

没太理解你的意思,难道不是写三个函数就行了吗?

def parse(self, response):
    ...
    # 分类
    if xxx:
        ...
        yield scrapy.Request(url, callback=self.getnews_1)
    elif yyy:
        ...
        yield scrapy.Request(url, callback=self.getnews_2)
    elif zzz:
        ...
        yield scrapy.Request(url, callback=self.getnews_3)

def getnews_1(self, response):
    news_item = PuluosiNewsItem()
    news_item['xx'] = yy
    ...
    yield news_item
    
def getnews_2(self, response):
    news_item = PuluosiNewsItem()
    news_item['xx'] = yy
    ...
    yield news_item
    
def getnews_3(self, response):
    news_item = PuluosiNewsItem()
    news_item['xx'] = yy
    ...
    yield news_item

解决了,可以参考采纳答案,或者参考我自己这个。
可以重写start_urls函数,直接请求三个url,调用三个函数,每个函数都yield item。

def start_requests(self):
    yield scrapy.Request('https://www.glprop.com.cn/press-releases.html', self.parse1)
    yield scrapy.Request('https://www.glprop.com.cn/in-the-news.html', self.parse2)
    yield scrapy.Request('https://www.glprop.com.cn/proposed-privatization.html', self.parse3)

def parse1(self, response):
    item=PuluosiNewsItem()
    yield item
    
def parse2(self, response):
    item=PuluosiNewsItem()
    yield item         
def parse3(self, response):
    item=PuluosiNewsItem()
    yield item  
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题