繁体   English   中英

如何将此代码的输出写入HTML文件?

[英]How to write the output of this code to HTML file?

from HTMLParser import HTMLParser

from urllib import urlopen

class Spider(HTMLParser):

        def __init__(self, url):
                HTMLParser.__init__(self)
                req = urlopen(url)
                self.feed(req.read())

        def handle_starttag(self, tag, attrs):
                if tag == 'a' and attrs:
                        print "Found link => %s" % attrs[0][1]

Spider('http://stackoverflow.com/questions/tagged/python')
python spider.py > output.html

把它放在脚本的顶部:

import sys
sys.stdout = file('output.html', 'w')

这会将脚本写入标准输出(包括print语句)的所有内容重定向到文件'output.html'。

我根本没有搞过Spider,但它是打印html,还是只打印“找到链接...”行? 如果你只是打印那些,你可以做一些像outfl = open('output.txt')

然后,而不是print ,调用outfl.write("Found link => %s" % attrs[0][1])

你可以随时写出<html><head></head><body> ,如果你需要HTML格式的话,可以写出</body></html> 另外,使用outfl = open('output.html')而不是.txt作为文件名。

我完全错过了这个问题吗? 如果你想要更好的答案,你应该更好地描述这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM