我写了一个脚本从一个网站上抓取数据。当我用“python”运行它时,它就工作了脚本.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)
这是我的壳的结果
^{pr2}$
脚本仍然打印出最后一行完成!数据打印到文件kq.txt文件但事实并非如此。如果我把kq.txt文件文件,很好用。如果我改变一下kq.txt文件(换个数字),也很管用。在
有人能解释一下为什么吗?
谢谢