python - 如何使用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)
给定输出: 无 无 测试 测试 无
异常输出:测试测试
我该怎么做,或者有没有其他方法。
解决方案
你需要跳过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
推荐阅读
- git - Git 推送到远程而不拉取并防止远程文件被删除
- c# - 如何旋转 ImageDrawing?
- python - Python - 在 Windows 上设置 python 路径的更快方法?
- c# - 在比较预期/实际之前,XUnit 未在字符串中执行代码
- csv - SQLCMD 将“7 k”字符串更改为 7k 或 7,000?
- java - 指南针覆盖地图使用 osmdroid 6.1
- tensorflow - 使用 Keras 将 theano 后端转换为 tensorflow 后端需要什么?
- parameter-sets - 如何增加 TFS 中的参数集限制?
- matlab - 在matlab中将向量拆分为更小的向量
- c - 按下鼠标按钮时如何打印连续消息(g_timeout_add)?