关于python 2.7:在BeautifulSoup 4.6的两个HTML标记之间提取HTML

Extract the HTML from between two HTML tags in BeautifulSoup 4.6

我想使用bs4在两个标签之间获取HTML。有没有办法在Beautiful Soup中使用javascript.innerHTML?

这是找到具有\\ title \\类的跨度并从中获取文本的代码。

1
2
3
def get_title(soup):
title = soup.find('span', {'class': 'title'})
return title.text.encode('utf-8')

此函数错误地返回了没有下标的跨度文本。 'Title about H2O and CO2'

以下代码是title = soup.find('span', {'class': 'title'})的结果:

1
<span class="title">Title about H<sub>2</sub>O and CO<sub>2</sub></span>

如何在没有原始跨度的情况下获得结果?

所需结果:'Title about H<sub>2</sub>O and CO<sub>2</sub>'


在发现JavaScript具有.innerHTML之后,我得以用谷歌搜索的方式来制作精美的汤。我找到了这个问题的答案。

在使用BS4选择元素之后,可以使用.decode_contents(formmater='html')获取innerHTML。

1
element.decode_contents(formatter="html")