Python 如何使用beautifulsoup跳过标记
如果我有下面的html结构,如何只打印“打印此”文本Python 如何使用beautifulsoup跳过标记,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,如果我有下面的html结构,如何只打印“打印此”文本 跳过这个 跳过这个 打印这个 谢谢您可以为此使用内容 from bs4 import BeautifulSoup soup = BeautifulSoup("""<div class="a"> <div> <strong> Skip this </strong> <span> skip this </span> </div&g
跳过这个
跳过这个
打印这个
谢谢您可以为此使用内容
from bs4 import BeautifulSoup
soup = BeautifulSoup("""<div class="a">
<div>
<strong>
Skip this
</strong>
<span>
skip this
</span>
</div>
print this
</div>""")
# the text you need is the last element of the contents
soup.find('div', {'class': 'a'}).contents[-1].strip()
# u'print this'
从bs4导入美化组
汤=美汤
跳过这个
跳过这个
打印这个
""")
#您需要的文本是内容的最后一个元素
soup.find('div',{'class':'a'}).contents[-1].strip()
#你“打印这个”
您好,我有一个后续问题。一些数据在文本后面有,有没有办法处理?例如谢谢跳过这个跳过这个打印这个
不太清楚你的文档是什么样子的。如果是instance(x,NavigableString)和x.strip()!=”,您可以尝试类似于
next(x代表x在倒转的(soup.find('div',{class':'a').contents)中的x)
。从内容末尾进行检查,过滤掉标记和空字符串。
from bs4 import BeautifulSoup
soup = BeautifulSoup("""<div class="a">
<div>
<strong>
Skip this
</strong>
<span>
skip this
</span>
</div>
print this
</div>""")
# the text you need is the last element of the contents
soup.find('div', {'class': 'a'}).contents[-1].strip()
# u'print this'