python - BeautifulSoup 在标签中找不到文本
问题描述
它看起来很简单,但我没有发现错误,我现在已经花了几个小时来解决这个问题:
from bs4 import BeautifulSoup
txt = "<HTML><BODY><TABLE><TR><TD><P>Net sales</P></TD></TR></TABLE></BODY></HTML>"
print(txt)
bs = BeautifulSoup(txt, 'html.parser')
q = bs.find(tag='p', text='Net sales')
# table = q.find_parent('table')
print("q = ", q)
这导致(在 Jupyter 中)
<HTML><BODY><TABLE><TR><TD><P>Net sales</P></TD></TR></TABLE></BODY></HTML>
q = None
为什么找不到文本“净销售额”?
最后,我想获取表格标签中的文本,我只是在上面的代码中注释了该行。
解决方案
尝试不使用 'tag' 参数
前任:
from bs4 import BeautifulSoup
txt = "<HTML><BODY><TABLE><TR><TD><P>Net sales</P></TD></TR></TABLE></BODY></HTML>"
bs = BeautifulSoup(txt, 'html.parser')
print bs
q = bs.find('p', text='Net sales')
# table = q.find_parent('table')
print("q = ", q)
输出:
('q = ', <p>Net sales</p>)
推荐阅读
- c# - FieldInfo.GetValue() 为嵌套的静态类公共静态字段返回 null
- java - 在 Groovy 中使用 JsonBuilder 序列化 java.nio.file.Path
- python - 使用 Keras 实现多输入多模型
- reactjs - 多次执行handleClick
- python - pymongo update_one 不基于 _id 更新
- angular - Angular App 无需重新编译即可动态加载插件
- azure - Azure KeyVault Secret 即将到期列表以电子邮件形式作为通知
- r - 如何绘制多个个体的平均时间序列
- python - 使用 python 代码中的参数运行 R 脚本
- linux - Linux 64bits:使用 cmake 交叉编译 32bits 目标