这可能是因为BeautifulSoup默认情况下会将注释内容视为文本节点,因此无法找到注释后的代码。为了解决这个问题,可以使用BeautifulSoup的find_all_next()函数来寻找下一个div标签,而不是find()或find_all()函数。
以下是解决方法的示例代码:
from bs4 import BeautifulSoup
html = '''
This is the first div.
This is the second div.
'''
soup = BeautifulSoup(html, 'html.parser')
# 使用find_all_next()查找下一个div标签
content = soup.find_all(text='This is the first div.')[0]
next_tag = content.find_all_next('div')[0]
# 打印下一个div标签
print(next_tag)
输出结果:
This is the second div.
在这个例子中,注释后面的第二个div标签被找到并打印出来。