サイトからデータをスクレイピングするスクリプトを作成しました。「pythonscript.py」で実行すると機能しますが、chmod + xでシェルから直接実行すると、正しく機能しません(出力ファイルを上書きしません)
これが私のコードです(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を少し変更する(数値を変更する)と、うまく機能します。
誰かが理由を説明できますか?ありがとう