废表列和行

2024-09-27 21:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想刮掉这个页面的表,但是废弃的数据只在一列中,而且在某些情况下数据不会出现。另外,我使用shell查看Xpath是否正确(我使用Xpath助手来标识这些Xpath)

import scrapy
class ToScrapeSpiderXPath(scrapy.Spider):
    name = 'scrape-xpath'
    start_urls = [
        'http://explorer.eu/contents/food/28?utf8=/',
    ]

    def parse(self, response):
        for flv in response.xpath('//html/body/main/div[4]'):

            yield {
                'Titulo': flv.xpath('//*@id="chromatography"]/table/tbody/tr[3]/th/strong/a/text()"]/tbody/tr[5]/td[3]/a[2]').extract(),
            'contenido': flv.xpath('//*@id="chromatography"]/table/tbody/tr[5]/td[3]/a[2]/text()').extract(),
             'clase': flv.xpath('//*[@id="chromatography"]/table/tbody/tr[5]/td[1]/text()').extract(),
            'Subclase': flv.xpath('//*[@id="chromatography"]/table/tbody/tr[5]/td[2]/a/text').extract(),
        }

Tags: 数据textidresponsetableextract页面xpath
2条回答

从给定的示例URL来看,对于包含更多记录的页面,其值应该是什么以及提取应该如何进行泛化并不十分明显。所以我尝试了一个不同的页面,包含多个记录,让我们看看结果是否符合您的需要。下面是准备运行的代码:

# -*- coding: utf-8 -*-
import scrapy

class PhenolExplorerSpider(scrapy.Spider):
    name = 'phenol-explorer'
    start_urls = ['http://phenol-explorer.eu/contents/food/29?utf8=/']

    def parse(self, response):
        chromatography = response.xpath('//div[@id="chromatography"]')
        title = chromatography.xpath('.//tr/th[@class="outer"]/strong/a/text()').extract_first()
        for row in chromatography.xpath('.//tr[not(@class="header")]'):
            class_ = row.xpath('./td[@rowspan]/text()').extract_first()
            if not class_:
                class_ = row.xpath('./preceding-sibling::tr[td[@rowspan]][1]/td[@rowspan]/text()').extract_first()
            subclass = row.xpath('./td[not(@rowspan)][1]/a/text()').extract_first()
            #content = row.xpath('./td[not(@rowspan)][2]/a[2]/text()').extract_first()
            content = row.xpath('./td[not(@rowspan)][2]/text()').extract_first()
            yield {
                'title': title.strip(),
                'class': class_.strip(),
                'subclass': subclass.strip(),
                'content': content.strip(),
            }

基本上,它迭代表的各个行,并从相应的字段中提取数据,一旦收集到完整的信息,就生成一个项。在

试试这个:

for row in response.css('#chromatography table tr:not(.header)'):
    yield {'titulo': row.xpath('./preceding-sibling::tr/th[contains(@class, "outer")]//a/text()').extract_first().strip(),
           'clase': row.xpath('./preceding-sibling::tr/th[contains(@class, "inner")]//text()').extract_first().strip(),
           'subclase': row.xpath('./td[2]//text()').extract_first().strip(),
           'contenido': row.css('.content_value a::text').extract_first().strip()}

请记住,内部循环选择器也应该是相对于节点flv的,使用//进行选择是一个全局选择器,因此它将获取所有内容。 最好检查真实的html代码,因为浏览器可能会呈现与实际接收到的html不同的其他代码(例如tbody标记)

相关问题 更多 >

    热门问题