【问题标题】:Wikipedia scraping - need assitance to structure it维基百科抓取 - 需要帮助来构建它
【发布时间】:2019-08-07 09:54:08
【问题描述】:

我正在尝试抓取this Wikipedia page

我遇到了一些问题,希望得到您的帮助:

  1. 有些行有多个名称或链接,我希望将它们全部分配到正确的国家/地区。反正我能做到吗?

  2. 我想跳过“名称(本地)”列。我该怎么做?

  3. 如果我正在抓取“名称(本地)”列。我得到了一些乱码,无论如何要编码吗?

import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd

url = 'https://en.wikipedia.org/wiki/List_of_government_gazettes'
source = requests.get(url).text

soup = BeautifulSoup(source, 'lxml')
table = soup.find('table', class_='wikitable').tbody

rows = table.findAll('tr')

columns = [col.text.encode('utf').replace('\xc2\xa0','').replace('\n', '') for col in rows[1].find_all('td')]
print(columns)

【问题讨论】:

    标签: python pandas python-2.7 beautifulsoup wikipedia


    【解决方案1】:

    您可以使用 pandas 函数 read_html 并从 DataFrames 列表中获得第二个 DataFrame

    url = 'https://en.wikipedia.org/wiki/List_of_government_gazettes'
    df = pd.read_html(url)[1].head()
    print (df)
           Country/region                                              Name  \
    0              Albania       Official Gazette of the Republic of Albania   
    1              Algeria                                  Official Gazette   
    2              Andorra  Official Bulletin of the Principality of Andorra   
    3  Antigua and Barbuda              Antigua and Barbuda Official Gazette   
    4            Argentina     Official Gazette of the Republic of Argentina   
    
                                     Name (native)                    Website  
    0  Fletorja Zyrtare E Republikës Së Shqipërisë                 qbz.gov.al  
    1                   Journal Officiel d'Algérie              joradp.dz/HAR  
    2     Butlletí Oficial del Principat d'Andorra                www.bopa.ad  
    3         Antigua and Barbuda Official Gazette    www.legalaffairs.gov.ag  
    4    Boletín Oficial de la República Argentina  www.boletinoficial.gob.ar 
    

    如果检查输出有问题行26,因为维基页面中的数据也有错误。

    解决方案应按列名和行设置值:

    df.loc[26, 'Name (native)'] = np.nan 
    

    【讨论】:

    • 所以它比我简单得多,非常感谢!前往学习 Pandas 以及如何将此表转换为 csv。再次感谢@jezrael
    猜你喜欢
    • 2019-05-24
    • 2017-04-30
    • 2020-07-20
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多