私はウェブサイトのチャットルームにログインし、コンテンツをスクラップし、ファイルに書き込んでフォーマットします。それはうまくいきますが(ゆっくりですが)、チャットルームが実行時にどのように見えるのかしか分かりません。私がしたいことは違いを追加することです。2つのテキストファイルを比較して差分を1つに追加します
私はこれをやっていると思っていましたが、タイトルはマスターファイルと一時ファイルでした。マスターファイルは常に存在し、テンポラリファイルはマスタと比較して書き込まれます。 2つのファイルが比較され、2つのファイルの間に違いがあれば、tempからmasterにコピーされます。私は他のソリューションにもオープンしていますが、これは実行可能なもののようです。ファイルは常にローカルに保存され、プログラムもローカルで実行されます。
どこから始めるべきかわかりません。私のコードは以下の通りです。私はそれが乱雑であり、改訂を必要としていることを知っています。私はまだPythonの初心者です。
import mechanize
import fileinput
import re
from os import chdir
from os import environ
from time import strftime
home = environ['HOME']
file = "ChatLog_" + strftime("%F") + ".txt"
filename = home + "/" + file
chdir(home + '/Desktop/')
# get login forms
def select_form(form):
return form.attrs.get('id', None) == 'auth'
# authenticate and log raw chat
def auth():
br = mechanize.Browser()
br.set_handle_robots(False)
br.open('http://website.com/endpoint')
br.select_form(predicate=select_form)
br.form['name'] = "username"
br.form['pass'] = "password"
br.submit()
text_file = open(filename, 'w')
response = br.response().read()
text_file.write(response)
text_file.close()
n = 0
while n < 9999:
try:
auth()
# strip first line
with open(filename, 'r') as fin:
data = fin.read().splitlines(True)
with open(filename, 'w') as fout:
fout.writelines(data[2:])
# strip nbsp characters
with open(filename, 'r+') as f:
text = f.read()
text = re.sub(' ', '', text)
f.seek(0)
f.write(text)
f.truncate()
# strip #039 apostrophe characters
with open(filename, 'r+') as f:
text = f.read()
text = re.sub(''', '\'', text)
f.seek(0)
f.write(text)
f.truncate()
# strip everything that lives in and around brackets, i.e. HTML tags
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('<.*?>', '', text)
f.seek(0)
f.write(text)
f.truncate()
n = n + 1
print(n)
except KeyboardInterrupt: print("\nUser aborted."); quit()
「comm」unix utilを見てみましょうか? – lolopop