python爬虫小脚本
天朝上网需要经常改hosts文件的,你们都懂的。要在网上找啊,找到了还要复制粘贴,那叫一个麻烦啊。
我是出了名的懒人嘛,写个脚本干这事吧……
#!/usr/bin/env python
import urllib
import os
import platform
import shutil
#获取网页内容,网址是假的,我只是想说一下方法
r = urllib.urlopen('http://www.baidu.com/hosts.html')
for line in r:
if line.find('NEW HOSTS') >= 0:
url = line[line.find('http://'):][:line[line.find('http://'):].find('"')]
#设置hosts文件路径
if platform.system() == 'Windows':
sysdir = os.getenv('SystemDrive')
hostspath = sysdir + '/windows/system32/drivers/etc/hosts'
if platform.system() == 'Linux':
hostspath = '/etc/hosts'
#备份hosts文件
if os.path.isfile(hostspath+'_bak') == False:
shutil.copyfile(hostspath,hostspath+'_bak')
shutil.copyfile(hostspath+'_bak',hostspath)
#读取文件,准备添加
host = open(hostspath,'r')
content = host.read()
host.close()
r = urllib.urlopen(url)
#开始添加
for line in r:
line=line.strip('\n')
content = content + line
#写入并关闭文件
host = open(hostspath,'w')
host.write(content)
host.close() 相关推荐
夜斗不是神 2020-11-17
染血白衣 2020-11-16
ARCXIANG 2020-11-02
CycloneKid 2020-10-27
meylovezn 2020-08-28
囧芝麻 2020-08-17
数据挖掘工人 2020-08-15
cxcxrs 2020-07-28
dashoumeixi 2020-07-20
sunzhihaofuture 2020-07-19
我欲疾风前行 2020-07-06
sunzhihaofuture 2020-07-04
Dimples 2020-06-28