【问题标题】:Scraping table in wikipedia with Python用 Python 抓取维基百科中的表格
【发布时间】:2020-03-25 14:59:35
【问题描述】:

我想在这个维基百科page 中用多伦多的邮政编码刮桌子。

无论我使用 pandas 方法或 beautifulSoup,它都不起作用,尽管其他人报告它应该起作用。恳请您提供您的提示:

熊猫:

df = pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0]

美丽的汤:

根据其他人的说法,使用图像中代码的输出表应该是图像中的表'expexted output with beautifulSoup'

beautifulSoup 的输出

beautifulSoup 的预期输出

【问题讨论】:

  • 不确定pandas 是否有神奇的方法,但你为什么不这样刮:for each td in for each tr, postal code = text inside <p>, if not <a> in <span> status = not_assigned else borough: text in first <a>, neighborhood: text in second <a>

标签: python pandas beautifulsoup


【解决方案1】:

你要求太多了! Pandas 擅长解析矩形 HTML 表格,在这里它完美地完成了:

  • 它提供了从 M1x 到 M9x 的 9 列
  • 它给出了从 MyA 到 MyZ 的 20 行(不使用所有字母)

在这里你想让它解析内部单元格。抱歉,您必须自己编写代码。例如,您可以轻松地解析第一行:

df = pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0]
dfA = df.iloc[0].str.extractall(r'(M\d\w)([^\(\(]*)(?:\((.*)\))?')

它给dfA

           0                                             1                                  2
  match                                                                                      
0 0      M1A                                  Not assigned                                NaN
1 0      M2A                                  Not assigned                                NaN
2 0      M3A                                    North York                          Parkwoods
3 0      M4A                                    North York                   Victoria Village
4 0      M5A                              Downtown Toronto         Regent Park / Harbourfront
5 0      M6A                                    North York  Lawrence Manor / Lawrence Heights
6 0      M7A  Queen's Park / Ontario Provincial Government                                NaN
7 0      M8A                                  Not assigned                                NaN
8 0      M9A                                     Etobicoke                   Islington Avenue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2019-05-24
    • 2016-09-08
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多