![](/img/trans.png)
[英]How to write the output to html file with Python BeautifulSoup
[英]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.