代码可以正常编译并按预期执行。但是,当我转到为应该被阻止的网站创建的网站列表中的一个网站时,我仍然可以转到该网站。即使它是我的python脚本应该阻止的五个网站之一,我仍然可以访问www.facebook.com
import time
from datetime import datetime as dt
host_temp="hosts.txt"
host_path=r"C:\Windows\System32\drivers\etc\hosts"
redirect="127.0.0.1"
website_list= ["https://www.facebook.com/","www.facebook.com","facebook.com","dub119.mail.live.
com","www.dub119.mail.live.com"]
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,0)<dt.now()< dt(dt.now().year,dt.now().month,dt.now().day,23):
print("Working hours...")
with open(host_path,'r+') as file:
content=file.read()
# print(content)
for website in website_list:
if website in content:
pass
else:
file.write(redirect+" "+website+"\n")
else:
with open(host_path,'r+') as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in website_list):
file.write(line)
file.truncate()
print("Fun hours..")
time.sleep(4)
我以管理员身份运行此代码,所以我知道那不是问题:enter image description here
答案 0 :(得分:0)
file.write(redirect+" "+website+"\r\n")
您需要使用Windows行尾。另外请注意,主机文件应包含DNS条目,因此facebook.com
和www.facebook.com
有意义,但https://..
之类的URL没有意义。