首页 > 解决方案 > 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

为什么找不到文本“净销售额”?

最后,我想获取表格标签中的文本,我只是在上面的代码中注释了该行。

标签: pythonbeautifulsoup

解决方案


尝试不使用 '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>)

推荐阅读