【发布时间】:2019-08-20 10:29:38
【问题描述】:
我是 python 新手。我正在使用 python 设计一个报价应用程序。我正在使用 BeautifulSoup 从聪明的报价网站获取当天的报价。我会将其附加到文本文件中。在这里,如果已经添加了当天的报价,当我再次执行程序时,它应该跳过它。如何让它成为可能
代码如下:
from bs4 import BeautifulSoup
import socket
import requests
import subprocess
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'})
quoteday=image_quote['alt']
text_file = open("quotes.log", "a+")
text_file.write("%s"%timestamp+"\t"+"%s"% quoteday)
text_file.write("\n")
text_file.close()
return
quotenotify()
在文件中输出:
Mar 29 Where there is a great love, there are always wishes. - Willa Cather
Mar 29 Where there is great love, there are always wishes. - Willa Cather
【问题讨论】:
-
在写入文件之前,以读取模式打开它并检查
quoteday是否已经存在 -
感谢您的回答。我会尝试这种方式。
-
另外,文件处理最好使用
with -
还有,为什么
return是空的?
标签: python python-3.x string string-comparison