在python中获取xml或html文件标签之间的数据的简单方法?

时间:2010-01-19 23:07:58

标签: python html xml

我正在使用Python,需要在标签之间查找和检索所有字符数据:

<tag>I need this stuff</tag>

然后我想将找到的数据输出到另一个文件。我只是在寻找一种非常简单有效的方法来做到这一点。

如果您可以发布快速代码段来描绘易用性。因为我在理解解析器时遇到了一些麻烦。

6 个答案:

答案 0 :(得分:7)

没有外部模块,例如

>>> myhtml = """ <tag>I need this stuff</tag>
... blah blah
... <tag>I need this stuff too
... </tag>
... blah blah """
>>> for item in myhtml.split("</tag>"):
...   if "<tag>" in item:
...       print item [ item.find("<tag>")+len("<tag>") : ]
...
I need this stuff
I need this stuff too

答案 1 :(得分:2)

Beautiful Soup是Python的精彩HTML / XML解析器:

  

Beautiful Soup是一个Python HTML / XML   解析器专为快速周转而设计   屏幕抓取等项目。三   功能强大:

     
      
  1. 如果给你不好的标记,美丽的汤不会窒息。它会产生一个   解析树大致如同   你的原始文件很有意义。   这通常足以收集   你需要和逃跑的数据。
  2.   
  3. 美丽的汤提供了一些简单的方法和Pythonic习语   导航,搜索和修改   解析树:解剖a的工具包   记录并提取您需要的内容。   您不必创建自定义   每个应用程序的解析器。
  4.   
  5. Beautiful Soup会自动将传入的文档转换为Unicode   和传出的文件到UTF-8。您   不必考虑编码,   除非文件没有指明   编码和美丽的汤不能   自动检测一个。然后你必须   指定原始编码。
  6.   

答案 2 :(得分:2)

我非常喜欢解析为element tree,然后使用element.textelement.tail

它还有 xpath ,例如搜索

>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element html at b7d3f1ec>
>>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
>>> p
<Element p at 8416e0c>
>>> p.text
"Some text in the Paragraph"
>>> links = p.getiterator("a")  # Returns list of all links
>>> links
[<Element a at b7d4f9ec>, <Element a at b7d4fb0c>]
>>> for i in links:             # Iterates through all found links
...     i.attrib["target"] = "blank"
>>> tree.write("output.xhtml")

答案 3 :(得分:1)

我就是这样做的:

    (myhtml.split('<tag>')[1]).split('</tag>')[0]

告诉我它是否有效!

答案 4 :(得分:0)

使用xpath和lxml;

from lxml import etree

pageInMemory = open("pageToParse.html", "r")

parsedPage = etree.HTML(pageInMemory)

yourListOfText = parsedPage.xpath("//tag//text()")

saveFile = open("savedFile", "w")
saveFile.writelines(yourListOfText)

pageInMemory.close()
saveFile.close()

比美丽的汤快。

如果你想测试你的Xpath - 我找到了FireFox's Xpather extremely helpful

进一步说明:

答案 5 :(得分:0)

def value_tag(s):
    i = s.index('>')
    s = s[i+1:]
    i = s.index('<')
    s = s[:i]
    return s