解析xml文件以创建超链接

时间:2012-11-20 00:43:29

标签: python

1.我正在尝试读取标签“sanity_results”之间的xml文件(查看输入http://pastebin.com/p9H8GQt4)并打印输出

2.对于具有http://或//的行的任何行或部分,我希望它将“a href”超链接标记附加到链接,以便当我发布到电子邮件时,它们在电子邮件中显示为超链接< / p>

Input file(results.xml)
http://pastebin.com/p9H8GQt4


def getsanityresults(xmlfile):
    srstart=xmlfile.find('<Sanity_Results>')
    srend=xmlfile.find('</Sanity_Results>')
    sanity_results=xmlfile[srstart+16:srend].strip()
    sanity_results = sanity_results.replace('\n','<br>\n')
    return sanity_results

def main ():
xmlfile = open('results.xml','r')
contents = xmlfile.read()
testresults=getsanityresults(contents)
print testresults
for line in testresults:
        line = line.strip()
        //How to find if the line contains "http" or "\\" or "//" and append "a href"attribute
        resultslis.append(link)

如果名称 =='主要':     main()的

1 个答案:

答案 0 :(得分:0)

查看您的错误消息:

AttributeError: 'file' object has no attribute 'find'

然后查看main():您将open('results.xml', 'r')的结果输入getsanityresults。但open(...)会返回文件对象,而getsanityresults则希望xmlfile字符串

您需要提取xmlfile内容并提供该getsanityresults

要获取文件的内容,请阅读[python文档的这一部分] 9http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects)。

特别是尝试:

xmlfile = open('results.xml', 'r')
contents = xmlfile.read() # <-- this is a string
testresults = getsanityresults(contents) # <-- feed a string into getsanityresults
# ... rest of code