如何在BeautifulSoup中获取子元素的HTML表示?

zer*_*lus 3 python beautifulsoup

假设我的HTML是:

<html><body><span>This is my text</span></body></html>
Run Code Online (Sandbox Code Playgroud)

如何获得内部包含内容的字符串表示,即:

<span>This is my text</span>
Run Code Online (Sandbox Code Playgroud)

Tre*_*vor 9

要获取元素的html表示,只需使用内置str函数:

soup = BeautifulSoup("<html><body><span>This is my text</span></body></html>")
span = soup.find('span')
str(span) # Outputs '<span>This is my text</span>'
Run Code Online (Sandbox Code Playgroud)

  • BeautifulSoup与unicode一起使用.因此,最好使用`unicode`函数而不是`str`.Unicode可以与非罗马字符一起使用. (7认同)