gpt4 book ai didi

python - 如何使用漂亮的汤从 html 文档中获取 标签

转载 作者:可可西里 更新时间:2023-11-01 13:41:28 25 4
gpt4 key购买 nike

我怎样才能得到 <text>使用美丽汤的 html 文档中的标签 Abbot lab 10k filing

我想提取 <text></text> 的所有 child 的标签名称使用以下代码标记

from bs4 import BeautifulSoup
import urllib.request
url ='https://www.sec.gov/Archives/edgar/data/1800/000104746919000624/a2237733z10-k.htm'
htmlpage = urllib.request.urlopen(url)
soup = BeautifulSoup(htmlpage, "html.parser")
all_text = soup.find('text')
all_tags = all_text.contents
all_tags = [x.name for x in all_tags if x.name is not None]
print(all_tags)

但是上面的代码我得到的输出是 ['html'] .

Expected output:
['p','p','p','p','p','p','div','div','font','font', etc......]

最佳答案

您可以使用 CSS 选择器(用于打印标签文本的所有子元素):

for child in all_text.select('text *'):
print(child.name, end=' ')

打印:

br p font font b p font b br p font b div div ...

编辑:为了仅打印标签文本的直接子元素,您可以使用:

from bs4 import BeautifulSoup
import requests

url ='https://www.sec.gov/Archives/edgar/data/1800/000104746919000624/a2237733z10-k.htm'

htmlpage = requests.get(url)
soup = BeautifulSoup(htmlpage.text, "lxml")

for child in soup.select('text > *'):
print(child.name, end=' ')

关于python - 如何使用漂亮的汤从 html 文档中获取 <text> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56765933/

25 4 0