漂亮的汤和桌子刮擦-lxml vs html pars

2024-05-13 20:31:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用BeautifulSoup从网页中提取表格的HTML代码。

<table class="facts_label" id="facts_table">...</table>

我想知道为什么下面的代码与"html.parser"一起工作,如果我将"lxml""html.parser"更改为"lxml",则会返回none

#! /usr/bin/python

from bs4 import BeautifulSoup
from urllib import urlopen

webpage = urlopen('http://www.thewebpage.com')
soup=BeautifulSoup(webpage, "html.parser")
table = soup.find('table', {'class' : 'facts_label'})
print table

Tags: 代码fromimportparser网页htmltablelxml
1条回答
网友
1楼 · 发布于 2024-05-13 20:31:48

BeautifulSoup文档中有一个称为Differences between parsers的特殊段落,它声明:

Beautiful Soup presents the same interface to a number of different parsers, but each parser is different. Different parsers will create different parse trees from the same document. The biggest differences are between the HTML parsers and the XML parsers.

这种差异在非格式良好的HTML文档上变得很明显。

其寓意是您应该使用在特定情况下工作的解析器。

还要注意,您应该始终显式地指定要使用的解析器。这将帮助您在不同的计算机或虚拟环境上运行代码时避免意外。

相关问题 更多 >