-1

我正在制作一个项目,在该项目中我使用scrapy网站上抓取项目,但问题是,该网站第 2 页的 xpath 与其他页面的 xpath 不同。结果,我的蜘蛛只是从前两页中抓取项目,然后只是简单地爬过其他页面。我怎样才能让我的蜘蛛也刮掉页面的项目?

我还在这里包括了我的蜘蛛,以便您可以在需要时看穿我的蜘蛛。

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from project2.items import Project2Item
from scrapy.http import Request

class ProjectSpider(BaseSpider):
    name = "project2spider"
    allowed_domains = ["http://directory.thesun.co.uk/"]
    current_page_no = 1
    start_urls = [
        'http://directory.thesun.co.uk/find/uk/computer-repair'
        ]

    def get_next_url(self, fired_url):
        if '/page/' in fired_url:
            url, page_no = fired_url.rsplit('/page/', 1)
        else:
            if self.current_page_no != 1:
                #end of scroll
                return 
        self.current_page_no += 1
        return "http://directory.thesun.co.uk/find/uk/computer-repair/page/%s" % self.current_page_no

# the parse procedure, and here is the codes which declares which field to scrape. 
    def parse(self, response):
        fired_url = response.url
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//div[@class="abTbl "]')
   
        for site in sites:
            item = Project2Item()
            item['Catogory'] = site.select('span[@class="icListBusType"]/text()').extract()
            item['Bussiness_name'] = site.select('a/@title').extract()
            item['Description'] = site.select('span[last()]/text()').extract()
            item['Number'] = site.select('span[@class="searchInfoLabel"]/span/@id').extract()
            item['Web_url'] = site.select('span[@class="searchInfoLabel"]/a/@href').extract()
            item['adress_name'] = site.select('span[@class="searchInfoLabel"]/span/text()').extract()
            item['Photo_name'] = site.select('img/@alt').extract()
            item['Photo_path'] = site.select('img/@src').extract()
            #items.append(item)
            yield item
        next_url = self.get_next_url(fired_url)
        if next_url:
            yield Request(next_url, self.parse, dont_filter=True)
        

对于其他页面,我需要使用它:sites = hxs.select('//div[@class="icListItem"]')

我怎样才能将它包含在我的蜘蛛中,以便它也可以从其他页面中抓取项目..

目前它只是抓取第一两页并简单地爬过其他页面。

4

1 回答 1

0

到目前为止你尝试了什么?一种解决方案是在调用下一页时使用作为元数据传递的类似索引的参数。就像是:

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    2nd_xpath = False
    try:
        if response.meta['index'] > 1:
            2nd_xpath = True
        index = response.meta['index']
    except KeyError:
        index = 0
    sites = (hxs.select('//div[@class="icListItem"]') if 2nd_xpath
             else hxs.select('//div[@class="abTbl "]'))

    ...

    request = Request(next_url, self.parse, dont_filter=True)
    request.meta['index'] = index + 1
    yield request

该代码肯定可以改进,但你明白了。

于 2013-08-15T13:02:27.920 回答