37

html5libでbeautifulsoupを使用すると、html、head、bodyのタグが自動的に配置されます。

BeautifulSoup('<h1>FOO</h1>', 'html5lib') # => <html><head></head><body><h1>FOO</h1></body></html>

この動作をオフに設定できるオプションはありますか?

4

9 に答える 9

49
In [35]: import bs4 as bs

In [36]: bs.BeautifulSoup('<h1>FOO</h1>', "html.parser")
Out[36]: <h1>FOO</h1>

これにより、Pythonの組み込みHTMLパーサーを使用してHTMLが解析されます。ドキュメントの引用:

<body>html5libとは異なり、このパーサーはタグを追加して整形式のHTMLドキュメントを作成しようとはしません。lxmlとは異なり、<html>タグを追加する必要はありません。


html5libまたは、パーサーを使用して、次の要素を選択することもでき<body>ます。

In [61]: soup = bs.BeautifulSoup('<h1>FOO</h1>', 'html5lib')

In [62]: soup.body.next
Out[62]: <h1>FOO</h1>
于 2013-02-11T22:45:33.360 に答える
7

まず、スープのサンプルを作成しましょう。

soup=BeautifulSoup("<head></head><body><p>content</p></body>")

次のように指定することで、htmlとbodyの子を取得できますsoup.body.<tag>

# python3: get body's first child
print(next(soup.body.children))

# if first child's tag is rss
print(soup.body.rss)

また、unwrap()を使用して、body、head、およびhtmlを削除することもできます。

soup.html.body.unwrap()
if soup.html.select('> head'):
    soup.html.head.unwrap()
soup.html.unwrap()

xmlファイルをロードすると、bs4.diagnose(data)を使用するように指示されますがlxml-xml、これはスープをラップしませんhtml+body

>>> BS('<foo>xxx</foo>', 'lxml-xml')
<foo>xxx</foo>
于 2018-08-14T08:02:39.060 に答える
7

BeautifulSoupのこの側面は、常に私を悩ませてきました。

これが私がそれに対処する方法です:

# Parse the initial html-formatted string
soup = BeautifulSoup(html, 'lxml')

# Do stuff here

# Extract a string repr of the parse html object, without the <html> or <body> tags
html = "".join([str(x) for x in soup.body.children])

簡単な内訳:

# Iterator object of all tags within the <body> tag (your html before parsing)
soup.body.children

# Turn each element into a string object, rather than a BS4.Tag object
# Note: inclusive of html tags
str(x)

# Get a List of all html nodes as string objects
[str(x) for x in soup.body.children]

# Join all the string objects together to recreate your original html
"".join()

私はまだこれが好きではありませんが、それは仕事を成し遂げます。BS4を使用してHTMLドキュメントから特定の要素や属性をフィルタリングしてから、BS4で解析されたオブジェクトではなく、オブジェクト全体を文字列reprとして戻す必要がある場合は、常にこれに遭遇します。

うまくいけば、次に私がこれをグーグルで検索するとき、私はここで私の答えを見つけるでしょう。

于 2019-12-17T23:23:11.597 に答える
4

唯一のオプションはhtml5lib、データの解析に使用しないことです。

html5libこれはライブラリの機能であり、不足している必須要素を追加するなど、不足しているHTMLを修正します。

于 2013-02-11T22:42:43.387 に答える
1

さらに別の解決策:

from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p><p>Hi!</p>', 'lxml')
# content handling example (just for example)
# replace Google with StackOverflow
for a in soup.findAll('a'):
  a['href'] = 'http://stackoverflow.com/'
  a.string = 'StackOverflow'
print ''.join([unicode(i) for i in soup.html.body.findChildren(recursive=False)])
于 2016-07-18T05:20:11.027 に答える
1
html=str(soup)
html=html.replace("<html><body>","")
html=html.replace("</body></html>","")

html/bodyタグブラケットを削除します。より洗練されたバージョンでは、startsWith、endsWith...もチェックされます。

于 2021-03-14T12:50:19.993 に答える
0

見栄えを良くしたい場合は、次のことを試してください。

BeautifulSoup([分析したいコンテンツ] .prettify()

于 2018-10-01T12:53:41.460 に答える
0

これが私のやり方です

a = BeautifulSoup()
a.append(a.new_tag('section'))
#this will give you <section></section>
于 2020-11-21T22:52:17.230 に答える
-1

v4.0.1以降、メソッドがありdecode_contents()ます。

>>> BeautifulSoup('<h1>FOO</h1>', 'html5lib').decode_contents()
'<h1>FOO</h1>' 

この質問の解決策の詳細: https ://stackoverflow.com/a/18602241/237105

于 2020-07-09T17:51:33.620 に答える