我写了一个脚本来从网站上抓取数据。当我使用“python script.py”运行它时它可以工作,但是当 chmod +x 并直接从 shell 运行时,它不能正常工作(不覆盖输出文件)
这是我的代码(尝试使用 HTMLParser):
#!/usr/bin/env python
from HTMLParser import HTMLParser
import urllib
import codecs
import string
FILE_NAME = 'kq.txt'
LINK = 'http://kqxs.vn/'
class MyHTMLParser(HTMLParser):
"""Parser get content in first table in site"""
def __init__(self):
self.reset()
self.fed = []
self.found = False
self.done = False
def handle_starttag(self, tag, attrs):
if tag == "table":
self.found = True
if tag == "/table":
self.found = False
def handle_endtag(self, tag):
if tag == "table":
self.done = True
def handle_data(self, data):
if self.found and not self.done:
self.fed.append(data)
def get_data(self):
return self.fed
#read data from URL
response = urllib.urlopen(LINK)
#print response.headers['content-type']
html = response.read()
html = unicode(html, 'utf-8')
parser = MyHTMLParser()
parser.feed(html)
result = parser.get_data()
#write to file
fw = codecs.open(FILE_NAME, 'w', 'utf-8')
#line.strip() remove string contains only spaces
#[fw.write(line + '\n') for line in result if line.strip()]
fw.writelines(line + '\n' for line in result if line.strip())
fw.close()
print "Done! data printed to file %s" %(FILE_NAME)
这是我的外壳的结果
famihug@hvn:/home/famihug%~/bin/leecher.py; cat ~/bin/kq.txt [0]
Done! data printed to file kq.txt
Giải đặc biệt
**92296**
**(HERE I RUN IT FROM INSIDE VIM with !python %)**
famihug@hvn:/home/famihug/bin%vim leecher.py [0]
Done! data printed to file kq.txt
Press ENTER or type command to continue
zsh: suspended vim leecher.py
famihug@hvn:/home/famihug/bin%cat kq.txt [20]
Giải đặc biệt
****88705****
famihug@hvn:/home/famihug/bin%/usr/bin/env python [0]
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
famihug@hvn:/home/famihug/bin%python [0]
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
脚本仍然打印出最后一行完成!数据打印到文件 kq.txt但实际上并没有。如果我删除 kq.txt 文件,它运行良好。如果我在 kq.txt 中稍作更改(更改一个数字),它也能正常工作。
谁能解释为什么?谢谢