首页 > 解决方案 > 根据列名刮取表格行

问题描述

我想提取表格,但问题是该网站中的所有表格每列在每个表格中都有不同的位置。可以根据列名,然后是该列的所有行来抓取

这是一个例子: 这是第一张桌子 这是第二张桌子

如您所见,所有列在表格中的位置不同

这是我的代码:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class LiSpider(CrawlSpider):
    name = 'li'
    allowed_domains = ['en.wikipedia.org']
    start_urls = ['https://en.wikipedia.org/wiki/List_of_defunct_airlines_of_the_Americas',
    'https://en.wikipedia.org/wiki/List_of_defunct_airlines_of_Asia',
    'https://en.wikipedia.org/wiki/List_of_defunct_airlines_of_Europe',
    'https://en.wikipedia.org/wiki/List_of_defunct_airlines_of_Oceania']

    rules = (
      
        Rule(LinkExtractor(restrict_xpaths='//div[text() = "Main article: "]/a'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
           for data in response.xpath('//table[@class="wikitable sortable"]/tbody/tr'):
            yield{
                'Airline': data.xpath('./td[1]/a/text()').get(),
                'IATA': data.xpath('./td[2]/text()').get(),
                'ICAO': data.xpath('./td[3]/text()').get(),
                'Image': data.xpath('./td[position() = count(//th[contains(.,"Image")]/following-sibling::th)+2]]/a/@href').get(),
                'Callsign': data.xpath('./td[5]/text()').get(),
                'Commensed Operations': data.xpath('./td[6]/text()').get(),
                'Ceased Operations': data.xpath('./td[7]/text()').get(),
                'Notes': data.xpath('./td[8]/text()').get(),
            }

标签: pythonweb-scrapingscrapy

解决方案


你可以使用熊猫。尝试这个:

import pandas as pd 
df = pd.read_html("https://en.wikipedia.org/wiki/List_of_defunct_airlines_of_Africa")

您将获得数据框列表


推荐阅读