首页 > 解决方案 > Python 3 BS4 - 从标签中提取数据(续)

问题描述

所以我有看起来像这样的 HTML 代码。

<li data-ng-repeat="sector in data.sectors"> <a target="_self" data-ng-href="/stocks/quotes/-382G/components/A" href="/stocks/quotes/-382G/components/A"><span>SIC-3826 Laboratory Analytical Instruments</span></a> </li>
 

我想提取跨度标签中的信息。不幸的是,当我使用以下代码时:

tags = soup.findAll("li",attrs={"data-ng-repeat":"sector in data.sectors"})
# tags = soup.find_all("a",attrs= {"target=","data-ng-href="})
# tags = soup.find_all("a")
for tag in tags:
print(tag.text)

结果是 [[sector.description]]。我要提取的是包括“SIC-3826 Laboratory Analytical Instruments”在内的信息

任何帮助将不胜感激。我尝试了各种替代方法,但我无法获得我想要的信息。

先感谢您!

标签: pythonbeautifulsouptags

解决方案


是的,您需要做的就是:

x = """<li data-ng-repeat="sector in data.sectors"> <a target="_self" data-ng-href="/stocks/quotes/-382G/components/A" href="/stocks/quotes/-382G/components/A"><span>SIC-3826 Laboratory Analytical Instruments</span></a> </li>"""

from bs4 import BeautifulSoup
print(BeautifulSoup(x, "lxml").text)

推荐阅读