Python 抓取嵌套URL

Python 抓取嵌套URL,python,python-3.x,xpath,web-scraping,scrapy,Python,Python 3.x,Xpath,Web Scraping,Scrapy,导言 由于我必须更深入地进行爬行,我面临着下一个问题:爬行嵌套页面,如: 我的爬虫必须从这个页面开始,进入并访问这个类别中列出的每个产品 对于每个类别中包含的每个产品,“Faltkartons”的每个子类别都应该这样做 已编辑 我的代码现在看起来像这样: import scrapy 从..项导入KartonageItem 卡顿蜘蛛类(刮毛蜘蛛): name=“卡尔顿12” 允许_域=['karton.eu'] 起始URL=[ 'https://www.karton.eu/Faltkartons'

导言

由于我必须更深入地进行爬行,我面临着下一个问题:爬行嵌套页面,如:

我的爬虫必须从这个页面开始,进入并访问这个类别中列出的每个产品

对于每个类别中包含的每个产品,“Faltkartons”的每个子类别都应该这样做

已编辑

我的代码现在看起来像这样:

import scrapy
从..项导入KartonageItem
卡顿蜘蛛类(刮毛蜘蛛):
name=“卡尔顿12”
允许_域=['karton.eu']
起始URL=[
'https://www.karton.eu/Faltkartons'
]
自定义_设置={'FEED_EXPORT_FIELDS':['SKU','Title','Link','Price','Delivery_Status','Weight','QTY','Volume']}
def解析(自我,响应):
url=response.xpath(“//div[@class=“cat缩略图”]”)
对于输入url:
link=a.xpath('a/@href')
yield response.follow(url=link.get(),callback=self.parse\u category\u cartons)
def parse_category_纸箱(自身、响应):
url2=response.xpath(“//div[@class=“cat缩略图”]”)
对于url2中的a:
link=a.xpath('a/@href')
yield response.follow(url=link.get(),callback=self.parse\u target\u页面)
def解析_目标_页面(自我,响应):
card=response.xpath('//div[@class=“text center articelbox”]”)
对于in卡:
items=KartonageItem()
link=a.xpath('a/@href')
items['SKU']=a.xpath('.//div[@class=“delivery status”]/small/text()).get()
items['Title']=a.xpath('.//h5[@class=“Title”]/a/text()).get()
items['Link']=a.xpath('.//h5[@class=“text center artikelbox”]/a/@href').extract()
items['Price']=a.xpath('.//strong[@class=“Price-ger-Price-text-nowrap”]/span/text()).get()
items['Delivery_Status']=a.xpath('.//div[@class=“signal_image Status-2”]/small/text()).get()
yield response.follow(url=link.get(),callback=self.parse_item,meta={'items':items})
def解析_项(自身、响应):
table=response.xpath('//div[@class=“产品信息内部”]”)
items=KartonageItem()
items=response.meta['items']
items['Weight']=a.xpath('.//span[@class=“staffelpreise small”]/text()).get()
items['Volume']=a.xpath('.//td[@class=“icon_content”][7]/text()).get()
收益项目
在我的脑海中,它从开始的url开始,然后我访问,寻找链接并跟随它们到达 。在该页面上,它会检查卡片上的一些信息,并按照特定产品页面的链接获取最后的项目

我的方法的哪部分是错误的? 我应该把我的课从“痒痒的蜘蛛”改成“爬行的蜘蛛”吗?或者这仅仅是我想设定一些规则时才需要的

仍然有可能,我对标题、sku等的XPath可能是错误的,但首先,我只想构建我的基础,对这些嵌套页面进行爬网

我的控制台输出:


最后,我设法浏览了所有这些页面,但不知何故,我的.csv文件仍然是空的

根据您提供的评论,问题始于您跳过了链中的一个请求

您的
start\u URL
将请求此页面: 页面将通过
parse
方法进行解析,并从到生成新请求

这些页面将在
parse_item
方法中解析,但它们不是您想要的最终页面。您需要在卡之间进行解析并生成新请求,如下所示:

for url in response.xpath('//div[@class="cat-thumbnails"]/div/a/@href')
    yield scrapy.Request(response.urljoin(url.get()), callback=self.new_parsing_method)
这里的示例,解析时将从中找到9个新链接

最后,您需要一个解析方法来刮取这些页面中的项目。由于有多个项,我建议您在for循环中运行它们。(您需要正确的xpath来刮取数据。)

编辑: 像现在一样重新编辑,我观察了页面结构,发现我的代码基于错误的假设。问题是有些页面没有子类别页面,有些页面有子类别页面

页面结构:

ROOT: www.karton.eu/Faltkartons
 |_ Einwellige Kartons
    |_ Subcategory: Kartons ab 100 mm Länge
      |_ Item List (www.karton.eu/einwellig-ab-100-mm)
        |_ Item Detail (www.karton.eu/113x113x100-mm-einwellige-Kartons)
    ...
    |_ Subcategory: Kartons ab 1000 mm Länge
      |_ ...
 |_ Zweiwellige Kartons #Same as above
 |_ Lange Kartons #Same as above
 |_ quadratische Kartons #There is no subcategory
    |_ Item List (www.karton.eu/quadratische-Kartons)
      |_ Item Detail (www.karton.eu/113x113x100-mm-einwellige-Kartons)
 |_ Kartons Höhenvariabel #There is no subcategory
 |_ Kartons weiß #There is no subcategory
下面的代码将从带有子类别的页面中删除项目,因为我认为这是您想要的。无论哪种方式,我都留下了一个
print
语句,向您显示由于没有子类别页面而将被跳过的页面。以防以后要包含它们

import scrapy
from ..items import KartonageItem

class KartonSpider(scrapy.Spider):
    name = "kartons12"
    allow_domains = ['karton.eu']
    start_urls = [
        'https://www.karton.eu/Faltkartons'
        ]
    custom_settings = {'FEED_EXPORT_FIELDS': ['SKU', 'Title', 'Link', 'Price', 'Delivery_Status', 'Weight', 'QTY', 'Volume'] } 
    
    def parse(self, response):
        url = response.xpath('//div[@class="cat-thumbnails"]')

        for a in url:
            link = a.xpath('a/@href')
            yield response.follow(url=link.get(), callback=self.parse_category_cartons)

    def parse_category_cartons(self, response):
        url2 = response.xpath('//div[@class="cat-thumbnails"]')

        if not url2:
            print('Empty url2:', response.url)

        for a in url2:
            link = a.xpath('a/@href')
            yield response.follow(url=link.get(), callback=self.parse_target_page)

    def parse_target_page(self, response):
        card = response.xpath('//div[@class="text-center artikelbox"]')

        for a in card:
            items = KartonageItem()
            link = a.xpath('a/@href')
            items ['SKU'] = a.xpath('.//div[@class="delivery-status"]/small/text()').get()
            items ['Title'] = a.xpath('.//h5[@class="title"]/a/text()').get()
            items ['Link'] = a.xpath('.//h5[@class="text-center artikelbox"]/a/@href').extract()
            items ['Price'] = a.xpath('.//strong[@class="price-ger price text-nowrap"]/span/text()').get()
            items ['Delivery_Status'] = a.xpath('.//div[@class="signal_image status-2"]/small/text()').get()
            yield response.follow(url=link.get(),callback=self.parse_item, meta={'items':items})

    def parse_item(self,response):
        table = response.xpath('//div[@class="product-info-inner"]')

        #items = KartonageItem() # You don't need this here, as the line bellow you are overwriting the variable.
        items = response.meta['items']
        items['Weight'] = response.xpath('.//span[@class="staffelpreise-small"]/text()').get()
        items['Volume'] = response.xpath('.//td[@class="icon_contenct"][7]/text()').get()
        yield items
笔记 更改为:

    card = response.xpath('//div[@class="text-center articelbox"]')
对此:(K而不是C)

对此进行了评论,因为meta中的项已经是
KartonageItem
。(您可以将其删除)

parse_items
方法中更改此

    items['Weight'] = a.xpath('.//span[@class="staffelpreise-small"]/text()').get()
    items['Volume'] = a.xpath('.//td[@class="icon_contenct"][7]/text()').get()
为此:

    items['Weight'] = response.xpath('.//span[@class="staffelpreise-small"]/text()').get()
    items['Volume'] = response.xpath('.//td[@class="icon_contenct"][7]/text()').get()

因为
a
在该方法中不存在。

我执行了你的爬行器,这里是它对我的行为:爬过
start\u URL
页面,在var
卡中选择了6个对象,每个对象都有一个链接。生成并爬网了6个请求,
parse_item
中的每个选择器返回空的,没有生成任何项。你能给我一个提示吗,我首先要纠正什么?递归爬虫总是必须使用规则吗?还是仍然可以不使用规则?我不清楚爬虫应该做什么。例如,您的爬行器到达此页面,但无法抓取任何内容,因为XPath(在
parse_item
方法中)与页面上的任何路径都不匹配(至少对我来说不匹配)。他们应该把内容刮到那里,还是像我的计划那样继续到下一页:它从第一个目的地开始,在访问该页之后,它应该从所有文章开始,并保存标题、链接、价格等值。这样做之后,它应该继续并重复它的工作。我的全部目标是,它对每一类的所有产品都能做到这一点。现在我开始重新检查xpathsdo,我需要在card变量之前使用for循环吗?或者我必须把它放在哪里?我想我不知怎么被卡住了。。我在
…cat缩略图“]/div/a/@h中也遇到了一个错误
    items['Weight'] = a.xpath('.//span[@class="staffelpreise-small"]/text()').get()
    items['Volume'] = a.xpath('.//td[@class="icon_contenct"][7]/text()').get()
    items['Weight'] = response.xpath('.//span[@class="staffelpreise-small"]/text()').get()
    items['Volume'] = response.xpath('.//td[@class="icon_contenct"][7]/text()').get()