BeautifulSoup - 我应该如何获得身体内容

Phi*_*ler 11 python django beautifulsoup html5lib

我正在HTML使用BeautifulSoup进行解析.最后,我想获取body内容,但没有body标签.但是BeautifulSoup增加html,headbody标签.我这个googlegrops讨论提出了一个可能的解决方案:

>>> from bs4 import BeautifulSoup as Soup
>>> soup = Soup('<p>Some paragraph</p>')
>>> soup.body.hidden = True
>>> soup.body.prettify()
u' <p>\n  Some paragraph\n </p>'
Run Code Online (Sandbox Code Playgroud)

这个解决方案是一个黑客.应该有一种更好,更明显的方法来做到这一点.

Azw*_*zwr 20

你的意思是在身体标签之间获取所有东西吗?

在这种情况下,您可以使用:

import urllib2
from bs4 import BeautifulSoup
page = urllib2.urlopen('some_site').read()
soup = BeautifulSoup(page)
body = soup.find('body')
the_contents_of_body_without_body_tags = body.findChildren()
Run Code Online (Sandbox Code Playgroud)

  • 我在使用findChildren时出现了一些问题,其中有些东西是冗余的,因为它们嵌套了多个层,并为每个包含层添加.为了从原始内容中获取内容而没有任何冗余或怪异,我使用了`pagefilling =''.join(['%s'%x代表在soup.body.contents中的x]) (4认同)
  • body.findChildren(递归=假);帮助您不要两次获得嵌套元素。 (2认同)

Jer*_*emy 5

我发现获取正文内容的最简单方法是unwrap()从正文标签内获取内容。

>>> html = "<p>Hello World</p>"
>>> soup = BeautifulSoup(html, "html5lib")
>>> print(soup)
<html><head></head><body><p>Hello World</p></body></html>
>>>
>>> soup.html.unwrap()
<html></html>
>>>
>>> print(soup)
<head></head><body><p>Hello World</p></body>
>>>
>>> soup.head.unwrap()
<head></head>
>>>
>>> print(soup)
<body><p>Hello World</p></body>
>>>
>>> soup.body.unwrap()
<body></body>
>>>
>>> print(soup)
<p>Hello World</p>
Run Code Online (Sandbox Code Playgroud)

为了提高效率和可重用性,您可以将那些不需要的元素放入列表中并循环遍历它们......

>>> def get_body_contents(html):
...  soup = BeautifulSoup(html, "html5lib")
...  for attr in ['head','html','body']:
...    if hasattr(soup, attr):
...      getattr(soup, attr).unwrap()
...  return soup
>>>
>>> html = "<p>Hello World</p>"
>>> print(get_body_contents(html))
<p>Hello World</p>
Run Code Online (Sandbox Code Playgroud)