使用 beautifulsoup,我可以使用以下代码抓取网页:
import requests
from bs4 import BeautifulSoup
page = requests.get("http://www.acbbroker.it/soci_dettaglio.php?r=3")
page
soup = BeautifulSoup(page.content, 'html.parser')
test = soup.find(id="paginainterna-content")
test_items = test.find_all(class_="entry-content")
tonight = test_items[0]
names = []
for x in tonight.find_all('a', itemprop="url"):
names.append(str(x))
print(names)
但我无法清理结果并仅获取 段落内的内容(还删除 href)。
这是我的结果的一小部分:
'<a href="http://www.google.com/maps/place/45.45249938964844,9.210599899291992" itemprop="url" target="_blank">A&B; Insurance e Reinsurance Brokers Srl</a>', '<a href="http://www.google.com/maps/place/45.647499084472656,8.774800300598145" itemprop="url" target="_blank">A.B.A. BROKERS SRL</a>', '<a href="http://www.google.com/maps/place/45.46730041503906,9.148480415344238" itemprop="url" target="_blank">ABC SRL BROKER E CONSULENTI DI ASSI.NE</a>', '<a href="http://www.google.com/maps/place/45.47710037231445,9.269220352172852" itemprop="url" target="_blank">AEGIS INTERMEDIA SAS</a>',
处理此类数据并获得干净结果的正确方法是什么?
谢谢
最佳答案
如果您只需要标签中的文本,请使用get_text()
方法
for x in tonight.find_all('a', itemprop="url"):
names.append(x.get_text())
print(names)
更好的列表理解
这是最快的
names = [x.get_text() for x in tonight.find_all('a', itemprop='url')]
关于python - 从 beautifulsoup 结果中删除 <a> HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514919/