不要把HTML,头部和身体自动标记,beautifulsoup [英] Don't put html, head and body tags automatically, beautifulsoup

查看:372
本文介绍了不要把HTML,头部和身体自动标记,beautifulsoup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用beautifulsoup与html5lib,它把HTML,头部和身体标记自动:

  BeautifulSoup('< H1>&FOO LT; / H1>','html5lib')#=> < HTML>< HEAD>< /头><身体GT;< H1> FOO< / H1>< /身体GT;< / HTML>

在那里,我可以设置,关闭此行为的任何选项?


解决方案

 在[35]:进口BS4为BS在[36]:bs.BeautifulSoup('< H1>&FOO LT; / H1>',html.parser)
出[36]:其中,H1>&FOO LT; / H1>

分析与Python的内置HTML解析器中的HTML。
引用文档:


  

不像html5lib,这种分析器没有试图创造一个良好的成形
  身体GT;通过增加一个&LT HTML文档标记。 lxml的不同,它甚至不
  懒得添加< HTML方式> 标签



另外,你可以使用 html5lib 解析器和后&LT只需选择元素;身体GT;

 在[61]:汤= bs.BeautifulSoup('< H1>&FOO LT; / H1>','html5lib')在[62]:soup.body.next
出[62]:其中,H1>&FOO LT; / H1>

using beautifulsoup with html5lib, it puts the html, head and body tags automatically:

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

is there any option that I can set, turn off this behavior ?

解决方案

In [35]: import bs4 as bs

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

This parses the HTML with Python's builtin HTML parser. Quoting the docs:

Unlike html5lib, this parser makes no attempt to create a well-formed HTML document by adding a <body> tag. Unlike lxml, it doesn’t even bother to add an <html> tag.


Alternatively, you could use the html5lib parser and just select the element after <body>:

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

In [62]: soup.body.next
Out[62]: <h1>FOO</h1>

这篇关于不要把HTML,头部和身体自动标记,beautifulsoup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆