我是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)
您需要更改逻辑以遍历行并检查是否存在小元素,如果它确实打印出该文本,则按现在的方式打印定位文本。你知道吗
在:
输出:
您可以使用
get_text()
来连接标记中的所有文本,strip=Ture
将删除字符串中的所有空间相关问题 更多 >
编程相关推荐