2 回答

TA貢獻1111條經驗 獲得超0個贊
繼續評論:
from bs4 import BeautifulSoup
import requests
import datetime
def quotenotify():
timestamp = datetime.datetime.now().strftime("%b %d")
res = requests.get('https://www.brainyquote.com/quote_of_the_day')
soup = BeautifulSoup(res.text, 'lxml')
image_quote = soup.find('img', {'class': 'p-qotd bqPhotoDefault bqPhotoDefaultFw img-responsive delayedPhotoLoad'})['alt']
with open("quotes.log", "w+") as f:
if image_quote not in f.read():
f.write("%s"%timestamp+"\t"+"%s"% image_quote + "\n")
quotenotify()
編輯:
由于使用該模式w+會截斷文件,我建議使用 pathlib:
from bs4 import BeautifulSoup
import requests
import datetime
from pathlib import Path
def quotenotify():
timestamp = datetime.datetime.now().strftime("%b %d")
res = requests.get('https://www.brainyquote.com/quote_of_the_day')
soup = BeautifulSoup(res.text, 'lxml')
image_quote = timestamp + "\t" + soup.find('img', {'class': 'p-qotd bqPhotoDefault bqPhotoDefaultFw img-responsive delayedPhotoLoad'})['alt']
with open("quotes3.log", "a+") as f:
contents = [Path("quotes3.log").read_text()]
print(contents)
print(image_quote)
if image_quote not in contents:
f.write("%s" % timestamp + "\t" + "%s" % image_quote + "\n")
quotenotify()

TA貢獻1921條經驗 獲得超9個贊
您應該首先以讀取模式打開文件并將內容加載到變量中。
您可以在下面的示例中看到,我將內容加載到變量中,然后僅當變量不在文本文件中時才附加到文件中。
text_file = open('test-file.txt', 'r+')
read_the_file = text_file.read()
text_file.close()
text_file = open('test-file.txt', 'a+')
new_string = 'Smack Alpha learns python'
if new_string not in read_the_file:
text_file.write(new_string + '\n')
text_file.close()
添加回答
舉報