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()
添加回答
举报