您好,欢迎来到外链网!
当前位置:外链网 » 站长资讯 » 专业问答 » 文章详细 订阅RssFeed

Python lxml,python lxml库

来源:互联网 浏览:113次 时间:2023-04-08

python爬虫解析HTML也是一项重要的任务,而选择合适的解析器就显得尤为重要了,下面为大家详细解析一下lxml解析库,

我信奉的是实践出真知,你看再多语法书不如自己动手敲出来,看看它到底实现的是什么功能,这样总比看书记得更加深刻吧。

pip install lxml后,把下面代码按着一点一点的敲出来执行一下吧,看见print你就可以执行一下,相信我,很好懂的。

# -*- coding: utf-8 -*-"""Created on Fri Apr 26 16:29:07 2019Describe:lxml是一个Python库,使用它可以轻松处理XML和HTML文件,还可以用于web爬取。市面上有很多现成的XML解析器,但是为了获得更好的结果,开发人员有时更愿意编写自己的XML和HTML解析器。这时lxml库就派上用场了。这个库的主要优点是易于使用,在解析大型文档时速度非常快,归档的也非常好,并且提供了简单的转换方法来将数据转换为Python数据类型,从而使文件操作更容易。@author: Grist Cheng"""from lxml import etree as etroot = et.Element('html',version="5.0")#root.append(et.SubElement('style'))et.SubElement(root,'head')et.SubElement(root,'title',bgcolor="red",fontsize='22')et.SubElement(root,'body',fontsize="15")print(et.tostring(root,pretty_print=True).decode("utf-8"))for e in root: print(e.tag) #遍历root结点中的所有子结点并打印他们的标签print("**************************************1")#使用属性root.set('newAttribute','attributeValue')print(et.tostring(root,pretty_print=True).decode("utf-8"))print("**************************************2")#获取属性的值print(root.get('newAttribute'))print(root[1].get('alpha')) # access title elementprint(root[1].get('bgcolor'))print("**************************************3")#从元素中检索文本root.text = "This is an HTML file" #add text to the Element and SubElementsroot[0].text="This is the head of the file"root[1].text="This is the title of the file"root[2].text="This is the body of the file and would contain paragraphs etc"print(et.tostring(root,pretty_print=True).decode("utf-8"))print("**************************************4")#检查元素是否有子,父元素print("检查根节点是否有子节点:")if len(root) > 0: #根节点是否有子节点+ print("True")else: print("False")print("检查根节点的子节点是否有子节点:")for i in range(len(root)): if(len(root[i]) > 0): print("True") else: print("False")print('\n')print("分别获取父元素:")print(root.getparent()) #根print(root[0].getparent())print(root[1].getparent())print('\n')print("检查title的同胞元素:")print(root[1].getnext())#root[1] is the title tag,this is find after the title tagprint(root[1].getprevious())#find before the title tagprint('\n')#解析原始xml和HTML文件print("解析原始xml和HTML文件,更改了HTML文档中的一些文本。由于我们传递给tostring函数一个xml_declaration参数,所以还自动添加了XML doctype声明:")root = et.XML('<html version="5.0" >This is an HTML file<head>This is the head of the file</head><title bgcolor="red" fontsize="22">This is the title of the file</title><body fontsize="15">This is the body of the file and would contain paragraphs etc</body></html>')root[1].text="The title text has changed!"print(et.tostring(root,xml_declaration=True).decode('utf-8'))print('\n')#寻找元素print(" 检查一些方法,通过这些方法,我们可以查看一个Element是否具有任何特定类型的子元素,以及它是否包含一些子元素。 ")print(root.find('a'))print(root.find('head').tag)print(root.findtext('title'))

?