首页 > 解决方案 > 如何使用bs4从div内的锚标记获取文本

问题描述

我是 bs4 的新手,我试图从 div 内的锚标记中提取文本,但它通过我出错。我的代码:从 bs4 导入 BeautifulSoup

data = '''<div class="one"><h2></h2></div>
<div class="one"><h1>Test 1</h1></div><div class="one">in <a href="https://www.example.com">Test Test</a></div>
<div class="one"><h2></h2></div>
<div class="two"><h2></h2></div>'''

soup = BeautifulSoup(data,'html.parser')

for div in soup.findAll('div', attrs={'class':'one'}):
    ss = div.find('a')
    print(ss)

给定输出: 无 无 测试 测试

异常输出:测试测试

我该怎么做,或者有没有其他方法。

标签: pythonpython-3.xbeautifulsoup

解决方案


你需要跳过None你可以这样做,if如下所示:

from bs4 import BeautifulSoup

data = '''
<div class="one"><h2></h2></div>
<div class="one"><h1>Test 1</h1></div>
<div class="one">in <a href="https://www.example.com">Test Test</a></div>
<div class="one"><h2></h2></div>
<div class="two"><h2></h2></div>
'''

soup = BeautifulSoup(data,'html.parser')
for div in soup.findAll('div', attrs={'class':'one'}):
    a_tag = div.find('a')
    if a_tag:
        print(a_tag.text)

输出:

Test Test

推荐阅读