我正在编写一个 python 程序,它从网页中获取信息并将其显示在 Gnome Shell 中的 Notification 上。我正在使用 Arch,所以我想在启动时启动这个程序,如果网页上有任何变化,它会通知我。这是我的代码:
import time
import webbrowser
import requests
from bs4 import BeautifulSoup
from gi.repository import Notify, GLib
IPS = {'Mobifone': True, 'Viettel': False, 'Vinaphone': False}
LINK = "https://id.vtc.vn/tin-tuc/chuyen-muc-49/tin-khuyen-mai.html"
def set_ips_state(ips_name, state):
global IPS
for key in IPS.iterkeys():
if key == ips_name:
IPS[key] = state
def call_webbrowser(notification, action_name, link):
webbrowser.get('firefox').open_new_tab(link)
def create_notify(summary, body, link):
Notify.init("Offer")
noti = Notify.Notification.new(summary, body, 'dialog-information')
noti.add_action('action_click', 'Read more...', call_webbrowser, link)
noti.show()
# GLib.MainLoop().run()
def save_to_file(path_to_file, string):
file = open(path_to_file, 'w')
file.write(string)
file.close()
def main():
global IPS
global LINK
result = []
offer_news = open('offer_news.txt')
tag_in_file = BeautifulSoup(offer_news.readline(), 'html.parser')
tag = tag_in_file.a
offer_news.close()
page = requests.get(LINK)
soup = BeautifulSoup(page.text, 'html.parser')
for div in soup.find_all('div', 'tt_dong1'):
# first_a = div.a
# main_content = first_a.find_next_subling('a')
main_content = div.find_all('a')[1]
for k, v in IPS.iteritems():
if v:
if main_content.text.find(k) != -1:
result.append(main_content)
print result[1].encode('utf-8')
if tag_in_file == '':
pass
else:
try:
old_news_index = result.index(tag)
print old_news_index
for idx in range(old_news_index):
create_notify('Offer News', result[idx].text.encode('utf-8'), result[idx].get('href'))
print "I'm here"
except ValueError:
pass
offer_news = open('offer_news.txt', 'w')
offer_news.write(result[0].__str__())
offer_news.close()
if __name__ == '__main__':
while 1:
main()
time.sleep(10)
问题是当我单击通知中的“阅读更多...”按钮时,除非我在 create_notify 函数中取消注释,否则它不会打开 Firefox GLib.MainLoop().run()
,但这会使程序冻结。有人可以帮忙吗?