0

我写了一个脚本来从网站上抓取数据。当我使用“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 中稍作更改(更改一个数字),它也能正常工作。

谁能解释为什么?谢谢

4

2 回答 2

1

我解决了我的问题!

因为我使用带有文件名的相对路径,所以当我运行时:

famihug@hvn:/home/famihug%~/bin/leecher.py; cat ~/bin/kq.txt                [0]

它在/home/famihug/中创建了一个新的kq.txt,而不是在/home/famihug/bin/ 这就是为什么当cat ~/bin/kq.txt

解决方案是:使用绝对路径而不是相对路径:

def fix_path(filename):
    filepath = os.path.realpath(__file__)
    path = os.path.dirname(filepath)
    fixed = os.path.join(path, filename)
    return fixed

fw = codecs.open(fix_path(FILE_NAME), 'w', 'utf-8')
于 2012-08-07T16:05:57.413 回答
-6

我不知道,但尝试 chmod 755 script_name 这可能是由于没有权限对过度文件。但实际上,我不知道,我无法测试它,因为我不在我的电脑上,我正在使用朋友的电脑。当我拿回我的电脑时,我会再次提问。

于 2012-07-06T03:06:30.560 回答