美丽的汤和餐桌刮面-LXML与HTML解析器 [英] Beautiful Soup and Table Scraping - lxml vs html parser

查看:71
本文介绍了美丽的汤和餐桌刮面-LXML与HTML解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to extract the HTML code of a table from a webpage using BeautifulSoup.

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

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

I would like to know why the code bellow works with the "html.parser" and prints back none if I change "html.parser" for "lxml".

#! /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

推荐答案

BeautifulSoup文档中有一个特殊段落,称为

There is a special paragraph in BeautifulSoup documentation called Differences between parsers, it states that:

Beautiful Soup将相同的界面呈现给许多不同的人 解析器,但是每个解析器都是不同的.不同的解析器将创建 同一文档中的不同解析树.最大的不同 在HTML解析器和XML解析器之间.

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文档中,差异显而易见.

The differences become clear on non well-formed HTML documents.

其道理是,您应该使用在特定情况下有效的解析器.

The moral is just that you should use the parser that works in your particular case.

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

Also note that you should always explicitly specify which parser are you using. This would help you to avoid surprises when running the code on different machines or virtual environments.

这篇关于美丽的汤和餐桌刮面-LXML与HTML解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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