要获取body标签的内容,可以使用BeautifulSoup的find()
方法或者CSS选择器来定位body标签。
以下是使用find()
方法的示例代码:
from bs4 import BeautifulSoup
html = '''
Example
Hello, World!
This is an example.
'''
soup = BeautifulSoup(html, 'html.parser')
body = soup.find('body')
if body:
print(body.text)
输出结果为:
Hello, World!
This is an example.
以下是使用CSS选择器的示例代码:
from bs4 import BeautifulSoup
html = '''
Example
Hello, World!
This is an example.
'''
soup = BeautifulSoup(html, 'html.parser')
body = soup.select_one('body')
if body:
print(body.text)
输出结果为:
Hello, World!
This is an example.
无论是使用find()
方法还是CSS选择器,都可以获取到body标签的内容。如果仍然无法获取到,可能是因为HTML代码中没有body标签或者BeautifulSoup解析出错了,请检查HTML代码和BeautifulSoup的使用方法。