在下面的示例中,如何使用BeauifulSoup解析数据?

2024-09-28 14:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python和BeautifulSoup的初学者,我正在尝试制作一个web scraper。然而,我面临着一些问题,无法找到出路。我的问题是:

这是HTML的一部分,我想从中删除:

<tr>
    <td class="num cell-icon-string" data-sort-value="6">
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a></td>

</tr>

<tr>
    <td class="num cell-icon-string" data-sort-value="6">
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a><br>
    <small class="aside">Mega Charizard X</small></td>
</tr>

现在,我想从第一行提取“Charizard”,从第二行提取“Mega Charizard X”。现在,我可以从两行中提取“Charizard”。你知道吗

这是我的密码:

#!/usr/bin/env python3

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("data.html"), "lxml")
poke_boxes = soup.findAll('a', attrs = {'class': 'ent-name'})

for poke_box in poke_boxes:
    poke_name = poke_box.text.strip()
        print(poke_name)

Tags: namefordatastringcellnumtrclass
2条回答

您需要更改逻辑以遍历行并检查是否存在小元素,如果它确实打印出该文本,则按现在的方式打印定位文本。你知道吗

soup = BeautifulSoup(html, 'lxml')
trs = soup.findAll('tr')
for tr in trs:
    smalls = tr.findAll('small')
    if smalls:
        print(smalls[0].text)
    else:
        poke_box = tr.findAll('a')
        print(poke_box[0].text)
import bs4
html = '''<tr>
    <td class="num cell-icon-string" data-sort-value="6">
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a></td>

</tr>

<tr>
    <td class="num cell-icon-string" data-sort-value="6">
    <td class="cell-icon-string"><a class="ent-name" href="/pokedex/charizard" title="View pokedex for #006 Charizard">Charizard</a><br>
    <small class="aside">Mega Charizard X</small></td>
</tr>'''
soup = bs4.BeautifulSoup(html, 'lxml')

在:

[tr.get_text(strip=True) for tr in soup('tr')]

输出:

['Charizard', 'CharizardMega Charizard X']

您可以使用get_text()来连接标记中的所有文本,strip=Ture将删除字符串中的所有空间

相关问题 更多 >

    热门问题