Skip to main content
 首页 » 编程设计

python之从包含其他标签的 "a"标签中提取文本的漂亮汤问题

2025年05月04日16wuhuacong

我想从如下所示的 HTML“a”标签中提取“climate 8/17/2019 2:00 PM”。 我编写了我认为会从“a”标签中提取所有文本的代码,稍后我将使用字符串操作提取所需的子字符串。

<div class="topic"> 
    <a class="class_a" href="/href_1" data1="" data2="hello" data3="Hi" date="Monday, August 17" time="2:00 PM" topic="climate 8/17/2019 2:00 PM"> 
            <span>2:00 PM</span> 
        <i class="Afternoon"></i> 
    </a> 
</div> 

我运行下面的代码,结果是:

2:00 PM 

我还更改了如下所示的行,但没有帮助。 bar = topics.find('a') 到 bar = topics.find('a', {"class": "class_a"})

我检查了 bar 变量的类型是类 bs4.element.Tag(不是字符串)

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
html = urlopen('https://tbd.com') 
bs = BeautifulSoup(html.read(), 'html.parser') 
 
topics = bs.findAll("div", {"class": "topic"}) 
for topic in topics: 
    bar = topic.find('a') 
    print (bar.text) 

请您参考如下方法:

如果您已经知道要从中提取文本的元素的类,那么您可以像任何 python 字典一样从它的属性中获取值:

from bs4 import BeautifulSoup 
 
h = """<div class="topic"> 
    <a class="class_a" href="/href_1" data1="" data2="hello" data3="Hi" date="Monday, August 17" time="2:00 PM" topic="climate 8/17/2019 2:00 PM"> 
            <span>2:00 PM</span> 
        <i class="Afternoon"></i> 
    </a> 
</div>""" 
 
soup = BeautifulSoup(h, "lxml") 
obj = soup.find('a', class_ = "class_a") 
 
print(obj.get('topic')) 
#climate 8/17/2019 2:00 PM