【问题标题】:Scrape tables from wiki. Python with bs4从 wiki 中抓取表格。 Python 与 bs4
【发布时间】:2021-02-21 05:37:33
【问题描述】:

我正在尝试从所有站点刮取一张桌子,但我停止了这个问题:我只刮取了一个单元格并且不知道我的问题在哪里。我需要从表that how i need 的所有行中刮取两个第一个单元格。以及如何手动将此代码修改为其他表?

我的代码:

from bs4 import BeautifulSoup
import requests

URL_TO = 'https://en.wikipedia.org/wiki/Rammstein_discography'
response = requests.get(URL_TO)
soup = BeautifulSoup(response.text,'html.parser')
soup.prettify()
table = soup.find("table", { "class" : "wikitable plainrowheaders" })
for row in table.findAll("tr"):
    cells = row.findAll("td")
    bells = row.findAll("th")
print(cells, bells)

我的输出:

[<td>
<ul><li>Released: 17 May 2019</li>
<li>Label: Universal</li>
<li>Format: CD, LP, DL</li></ul>
</td>, <td>1</td>, <td>5</td>, <td>1</td>, <td>1</td>, <td>1</td>, <td>1</td>, <td>1</td>, <td>1</td>, <td>1</td>, <td>2</td>, <td>1</td>, <td>3</td>, <td>9
</td>, <td>
<ul><li>FRA: 50,000 <sup class="reference" id="cite_ref-chartsinfrance_45-0"><a href="#cite_note-chartsinfrance-45">[45]</a></sup></li>
<li>GER: 260,000<sup class="reference" id="cite_ref-chartsinfrance_45-1"><a href="#cite_note-chartsinfrance-45">[45]</a></sup></li>
<li>US: 25,000<sup class="reference" id="cite_ref-46"><a href="#cite_note-46">[46]</a></sup></li>
<li>WW: 900,000<sup class="reference" id="cite_ref-47"><a href="#cite_note-47">[47]</a></sup></li></ul>
</td>, <td>
<ul><li>BVMI: 5× Gold<sup class="reference" id="cite_ref-musikindustrie_23-4"><a href="#cite_note-musikindustrie-23">[23]</a></sup></li>
<li>BEL: Gold<sup class="reference" id="cite_ref-48"><a href="#cite_note-48">[48]</a></sup></li>
<li>SNEP: Gold<sup class="reference" id="cite_ref-snep_44-1"><a href="#cite_note-snep-44">[44]</a></sup></li>
<li>IFPI AUT: 2× Platinum<sup class="reference" id="cite_ref-IFPIAUT_30-4"><a href="#cite_note-IFPIAUT-30">[30]</a></sup></li></ul>
</td>] [<th scope="row"><a href="/wiki/Untitled_Rammstein_album" title="Untitled Rammstein album">Untitled</a>
</th>]

我需要:

[Herzeleid]
[Released: 24 September 1995
Label: Motor, Slash
Format: CD, CS, LP, DL]

【问题讨论】:

    标签: python beautifulsoup python-requests wikipedia


    【解决方案1】:

    您可以使用pandas 进行表格抓取

    import pandas as pd
    
    URL_TO = 'https://en.wikipedia.org/wiki/Rammstein_discography'
    df = pd.read_html(URL_TO)
    df[1].loc[0, ['Title', 'Album details']].iloc[1]
    

    上面的0是第一个记录,Herzeleid

    Out[26]: 'Released: 24 September 1995 Label: Motor, Slash Format: CD, CS, LP, DL'

    你可以用

    保存表格
    df[1].loc[:, ['Title', 'Album details']].to_csv('text_file.csv', index=False)
    

    【讨论】:

    • 为什么我看不到“标题”?它可以在其他 wiki 表上工作吗?
    • df[1] 是整个表格,我刚刚切了第一个单元格,是的,您可以对网络上的所有表格使用 pandas
    • 如何单独显示“标题”?我可以链接到代码中这些命令的说明吗?
    • 你可以开始here
    猜你喜欢
    • 2021-07-08
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多