Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中从HTML文档中解析和提取特定元素?_Python_Xml Parsing_Lxml - Fatal编程技术网

如何在Python中从HTML文档中解析和提取特定元素?

如何在Python中从HTML文档中解析和提取特定元素?,python,xml-parsing,lxml,Python,Xml Parsing,Lxml,Python中有很多XML和HTML解析器,我正在寻找一种简单的方法来提取HTML文档的一部分,最好使用XPATH构造,但这只是可选的 这里有一个例子 src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>" src=“…aaabbccc…” 我想提取id=content的整个元素体,因此结果应该是

Python中有很多XML和HTML解析器,我正在寻找一种简单的方法来提取HTML文档的一部分,最好使用XPATH构造,但这只是可选的

这里有一个例子

src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>"
src=“…aaabbccc…”
我想提取id=content的整个元素体,因此结果应该是:
AAABBBCCC

如果我不安装新的库就可以做到这一点

我还希望获得所需元素的原始内容(未重新格式化)


不允许使用regexp,因为它们对于解析XML/HTML不安全。

要使用库进行解析,最好的方法是 这里是一个如何为您工作的片段

from BeautifulSoup import BeautifulSoup

src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>"
soupy = BeautifulSoup( src )

content_divs = soupy.findAll( attrs={'id':'content'} )
if len(content_divs) > 0:
    # print the first one
    print str(content_divs[0])

    # to print the text contents
    print content_divs[0].text

    # or to print all the raw html
    for each in content_divs:
        print each
从美化组导入美化组
src=“…aaabbccc…”
汤=美汤(src)
content\u divs=soupy.findAll(attrs={'id':'content'})
如果len(content_divs)>0:
#打印第一张
打印str(内容分区[0])
#打印文本内容的步骤
打印内容分区[0]。文本
#或者打印所有原始html
对于每个in-content\u div:
打印每个

是的,我已经这样做了。这可能不是最好的方法,但它的工作原理与下面的代码类似。我没有测试这个

import re

match = re.finditer("<div id=content>",src)
src = src[match.start():]

#at this point the string start with your div everything proceeding it has been stripped.
#This next part works because the first div in the string is the end of your div section.
match = re.finditer("</div>",src)
src = src[:match.end()]
重新导入
match=re.finditer(“,src)
src=src[match.start():]
#在这一点上,字符串从div开始,所有正在进行的操作都已被剥离。
#下一部分工作,因为字符串中的第一个div是div部分的结尾。
match=re.finditer(“,src)
src=src[:match.end()]
src现在在字符串中只包含后面的div。如果在某些情况下,您想要的内容中有另一个内容,那么您只需为您的re.finditer部分构建一个更丰富的搜索模式