python - 根据列名刮取表格行
问题描述
我想提取表格,但问题是该网站中的所有表格每列在每个表格中都有不同的位置。可以根据列名,然后是该列的所有行来抓取
如您所见,所有列在表格中的位置不同
这是我的代码:
# -*- 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(),
}
解决方案
你可以使用熊猫。尝试这个:
import pandas as pd
df = pd.read_html("https://en.wikipedia.org/wiki/List_of_defunct_airlines_of_Africa")
您将获得数据框列表
推荐阅读
- matlab - 如何将多张图像合并为一张并保存在matlab上?
- android - 使用 Kotlin 在 android 中初始化视图的编码标准
- javascript - 如何使用 Mysql 在 Node JS 中创建函数搜索?
- android - RecyclerView - 插入新项目时向下滚动
- authentication - 使用 Postman 进行 AAD B2C 授权的 Web Api 测试失败
- c# - 如何确保两个请求在不同时间发送?
- c# - 将值添加到列表 Linq 中的列表
- sql - 为什么我们不能使用减号关键字而不是减号
- java - 在openjdk中,安全策略没有生效
- html - 识别在 WSGI-Python 中从 HTML 中按下了哪个按钮(没有任何像烧瓶和 Django 这样的框架)?