【问题标题】:Unable to scrape the right wikitable with BeautifulSoup4 (beginner)无法使用 BeautifulSoup4 抓取正确的 wikitable(初学者)
【发布时间】:2020-07-24 20:02:48
【问题描述】:

这里是一个完整的初学者...我正在尝试从Wikipedia page 中刮取成分表,但是刮取的表是年度回报(第一个表)而不是我需要的成分表(第二个表)。有人可以帮忙看看是否有任何方法可以针对我想要使用 BeautifulSoup4 的特定表?

import bs4 as bs
import pickle
import requests

def save_klci_tickers():
    resp = requests.get ('https://en.wikipedia.org/wiki/FTSE_Bursa_Malaysia_KLCI')
    soup = bs.BeautifulSoup(resp.text)
    table = soup.find ('table', {'class': 'wikitable sortable'})
    tickers = []
    for row in table.findAll ('tr') [1:]:
        ticker = row.findAll ('td') [0].text
        tickers.append(ticker)

    with open ("klcitickers.pickle", "wb") as f:
        pickle.dump (tickers, f)

    print (tickers)
    return tickers


save_klci_tickers()

【问题讨论】:

    标签: python web-scraping beautifulsoup datatable wikipedia


    【解决方案1】:

    试试 pandas 库,眨眼之间就可以从该页面获取 csv 文件中的表格数据:

    import pandas as pd
    
    url = 'https://en.wikipedia.org/wiki/FTSE_Bursa_Malaysia_KLCI'
    
    df = pd.read_html(url, attrs={"class": "wikitable"})[1] #change the index to get the table you need from that page
    new = pd.DataFrame(df, columns=["Constituent Name", "Stock Code", "Sector"])
    new.to_csv("wiki_data.csv", index=False)
    print(df)
    

    如果您仍然想坚持使用 BeautifulSoup,则以下内容应该可以达到目的:

    import requests
    from bs4 import BeautifulSoup
    
    res = requests.get("https://en.wikipedia.org/wiki/FTSE_Bursa_Malaysia_KLCI")
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select("table.wikitable")[1].select("tr"):
        data = [item.get_text(strip=True) for item in items.select("th,td")]
        print(data)
    

    如果您想使用.find_all() 而不是.select(),请尝试以下操作:

    for items in soup.find_all("table",class_="wikitable")[1].find_all("tr"):
        data = [item.get_text(strip=True) for item in items.find_all(["th","td"])]
        print(data)
    

    【讨论】:

    • 谢谢先生!我使用您使用的索引编辑了代码,如下所示,它起作用了: table = soup.select ('table', {'class': 'wikitable sortable'}) [2] 非常感谢我的人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2019-06-25
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多