Python - Beautiful Soup,如何获取标签的第一个值

标签 python beautifulsoup

我有这个标签:

<span class="companyName">Actua Corp <acronym title="Central Index Key">CIK</acronym>#: <a href="/cgi-bin/browse-edgar?action=getcompany&amp;CIK=0001085621&amp;owner=include&amp;count=40">0001085621 (see all company filings)</a></span>

我将如何获得之后的值 <span class="companyName"> .

在这种情况下是 Actua Corp.

我对所有方法都持开放态度。

最佳答案

如果你只是想要Actua Corp,你可以使用next

r = '<span class="companyName">Actua Corp <acronym title="Central Index Key">CIK</acronym>#: <a href="/cgi-bin/browse-edgar?action=getcompany&amp;CIK=0001085621&amp;owner=include&amp;count=40">0001085621 (see all company filings)</a></span>'

from bs4 import BeautifulSoup    
soup = BeautifulSoup(r)

span = soup.find('span', {'class': 'companyName'})
print(span.next)
>>> Actua Corp

如果你想要span内的所有文本,你可以使用text

print(span.text)
>>> Actua Corp CIK#: 0001085621 (see all company filings)

关于Python - Beautiful Soup,如何获取标签的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44957121/

相关文章:

python - 定义类 : Module takes at most 2 arguments

Python:可能是列表也可能不是列表的参数的最佳实践

Python - 使用 BeautifulSoup 抓取 ESPN 表

python - Beautiful Soup 的空元素错误

Python去除空白美丽汤和条

带有简单网络包装器的 python tkinter

python - 使用 urllib2 HTTPS 登录

regex - BeautifulSoup.find 的返回值是多少?

python - 如何防止 PYTHON-DJANGO 中的 SQL 注入(inject)?

python - 使用 python 从桌面解析 HTML