首页 > 解决方案 > 我的代码在 Wikipedia 中找不到表格

问题描述

我正在尝试获取此维基百科页面上的最后一张表(标题为“Registro de los casos”)

使用此 python 3.7 代码

import requests
from bs4 import BeautifulSoup, NavigableString, Tag

def webcrawler():

    url = "https://es.wikipedia.org/wiki/Pandemia_de_enfermedad_por_coronavirus_de_2020_en_Argentina"#Cronolog%C3%ADa"
    page = requests.get(url)
    soup = BeautifulSoup(page.text,"html.parser")
    tables = soup.findAll("table", class_='wikitable')[0]
    #print(tables)

    for table in tables:
        if isinstance(table, NavigableString):
            continue
        ths = table.find_all('th')
        headings = [th.text.strip() for th in ths]
        print(headings)


webcrawler()

但它只找到第一个表,而不是最后一个。我究竟做错了什么?

标签: python-3.xbeautifulsoup

解决方案


您设置tables为返回的第一项soup.findAll("table", class_='wikitable')[0]。如果您取出,[0]则将具有该类的所有表写入表变量


推荐阅读