这篇文章主要介绍了Python利用Beautiful Soup模块创建对象的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
安装
通过 pip 安装 Beautiful Soup 模块:pip install beautifulsoup4
。
还可以使用 PyCharm IDE 来写代码,在 PyCharm 中的 Preferences 中找到 Project ,在里面搜索 Beautiful Soup 模块,进行安装即可。
创建 BeautifulSoup 对象
Beautiful Soup 模块广泛使用从网页中得到数据。我们能够使用 Beautiful Soup 模块从 HTML/XML 文档中提取任何数据,例如,网页中的所有链接或者标签内的内容。
为了实现这一点,Beautiful Soup 提供了不同的对象和方法。任何的 HTML/XML 文档能够转化成不同的 Beautiful Soup 对象,这些对象有着不同的属性和方法,我们能够从中提取到需要的数据。
Beautiful Soup 总共有如下三种对象:
BeautifulSoup
Tag
NavigableString
创建 BeautifulSoup 对象
创建一个 BeautifulSoup 对象是任何 Beautiful Soup 工程的起点。
BeautifulSoup 可以通过传一个字符串或者类文件对象(file-like object),例如机器上的文件或者网页。
通过字符串创建 BeautifulSoup 对象
在 BeautifulSoup 的构造器中通过传递一个字符串来创建对象。
helloworld = '<p>Hello World</p>' soup_string = BeautifulSoup(helloworld) print soup_string <html><body><p>Hello World</p></body></html>
通过类文件对象创建 BeautifulSoup 对象
在 BeautifulSoup 的构造器中通过传递一个类文件对象(file-like object)来创建对象。这在解析在线网页时非常有用。
url = "http://www.glumes.com" page = urllib2.urlopen(url) soup = BeautifulSoup(page) print soup
除了传递类文件对象之外,我们还可以传递本地文件对象到 BeautifulSoup 的构造器来生成对象。
with open('foo.html','r') as foo_file : soup_foo = BeautifulSoup(foo_file) print soup_foo
为 XML 解析创建 BeautifulSoup 对象
Beautiful Soup 模块同样能够用来解析 XML 。
当创建一个 BeautifulSoup 对象时, Beautiful Soup 模块将会选择合适的 TreeBuilder 类来创建 HTML/XML 树。默认情况下,选择 HTML TreeBuilder 对象,它将使用默认的 HTML 解析器,产生一个 HTML 结构树。在上面的代码中,由字符串生成 BeautifulSoup 对象,就是将它解析成了 HTML 树结构。
如果我们想要 Beautiful Soup 模块将输入的内容解析为 XML 类型,那么就需要在 Beautiful Soup 构造器中精确指定使用的 features 参数。通过特定的 features 参数,Beautiful Soup 将会选择最适合的 TreeBuilder 类来满足我们想要的特征。
理解 features 参数
每一个 TreeBuilder 根据它使用的解析器将会有不同的特征。因此,输入的内容根据传递到构造器的 features 参数也会有不同的结果。
在 Beautiful Soup 模块中,TreeBuilder 当前使用的解析器如下:
lxml
html5lib
html.parser
BeautifulSoup 构造器的 features 参数能够接受一个字符串列表或一个字符串值。
当前,每一个 TreeBuilder 支持的 features 参数和解析器如下表所示:
Features | TreeBuilder | Parser |
---|---|---|
[‘lxml','html','fast','permissive'] | LXMLTreeBuilder | lxml |
[‘html','html5lib','permissive','strict','html5′] | HTML5TreeBuilder | html5lib |
[‘html','strict','html.parser'] | HTMLParserTreeBuilder | html.parser |
[‘xml','lxml','permissive','fast'] | LXMLTreeBuilderForXML | lxml |
根据指定的 feature 参数,Beautiful Soup 将会选择最合适的 TreeBuilder 类。如果在指定对应的解析器时,出现如下的报错信息,可能就是需要安装对应的解析器了。
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: html5lib. Do you need to install a parser library?
就 HTML 文档而言,选择 TreeBuilder 的顺序是基于解析器建立的优先级,就如上表格所示的优先级。首先是 lxml ,其次是 html5lib ,最后才是 html.parser 。例如,我们选择 html 字符串作为 feature 参数,那么如果 lxml 解析器可用,则 Beautiful Soup 模块将会选择 LXMLTreeBuilder 。如果 lxml 不可用,则会选择 根据 html5lib 解析器选择 HTML5TreeBuilder 。如果在不可用,则会选择根据 html.parser 选择 HTMLParserTreeBuilder 了。
至于 XML ,由于 lxml 是唯一的解析器,所以 LXMLTreeBuilderForXML 总是会被选择的。
所以,为 XML 创建一个 Beautiful Soup 对象的代码如下:
helloworld = '<p>Hello World</p>' soup_string = BeautifulSoup(helloworld,features="xml") print soup_string
输入的结果也是 XML 形式的文件 :
在创建 Beautiful Soup 对象时,更好的实践是指定解析器。这是因为,不同的解析器解析的结果内容大不相同,尤其是在我们的 HTML 文档内容非法时,结果更为明显。
当我们创建一个 BeautifulSoup 对象时,Tag 和 NavigableString 对象也就创建了。
创建 Tag 对象
我们可以从 BeautifulSoup 对象中得到 Tag 对象,也就是 HTML/XML 中的标签。
如下 HTML 代码所示:
#!/usr/bin/python # -*- coding:utf-8 -*- from bs4 import BeautifulSoup html_atag = """ <html> <body> <p>Test html a tag example</p> <a href="http://www.glumes.com'>Home</a> <a href="http;//www.glumes.com/index.html'>Blog</a> </body> <html> """ soup = BeautifulSoup(html_atag,'html.parser') atag = soup.a print type(atag) print atag
从结果中可以看到 atag 的类型是 c02efc57cb50b3571070ba99b5a8455a 。而 soup.a 的结果就是 HTML 文档中的第一个 3499910bf9dac5ae3c52d5ede7383485 标签。
HTML/XML 标签对象具有名称和属性。名称就是标签的名字,例如 标签 3499910bf9dac5ae3c52d5ede7383485 的名称就是 a 。属性则是标签的 class 、id 、style 等。Tag 对象允许我们得到 HTML 标签的名称和属性 。
Tag 对象的名称
通过 .name 方式得到 Tag 对象的名称 。
tagname = atag.name print tagname
同时也能够改变 Tag 对象的名称:
atag.name = 'p'
这样就将上面 HTML 文档中的第一个 3499910bf9dac5ae3c52d5ede7383485 标签名称换成了 e388a4556c0f65e1904146cc1a846bee 标签了。
Tag 对象的属性
在 HTML 页面中,标签可能有不同的属性,例如 class 、id 、style 等。Tag 对象能够以字典的形式访问标签的属性。
atag = soup_atag.a print atag
也能通过 .attrs 的方式访问到,这样会将所有的属性内容都打印出来 :
print atag.attrs {'href': u'http://www.glumes.com'}
创建 NavigableString 对象
NavigableString 对象持有 HTML 或 XML 标签的文本内容。这是一个 Unicode 编码的字符串。
我们可以通过 .string 的方式得到标签的本文内容 。
navi = atag.string print type(navi) print navi.string
小结
代码小结如下:
BeautifulSoup
soup = BeautifulSoup(String)
soup = BeautifulSoup(String,features=”xml”)
Tag
tag = soup.tag
tag.name
tag[‘attribute']
NavigableString
soup.tag.string
总结
以上是Beautiful Soup模块在Python中创建对象的方法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Atom编辑器mac版下载
最流行的的开源编辑器

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)