MAGI的专栏 2018-03-12
内容:通过wget批量下载我自己安科网的随笔页面,看阅读量是否增加
环境:kali+python
思路:1、在终端利用调用脚本的方式执行python脚本,比如:python add_readcounts.py -f my_blogs
2、对爬虫不熟,但是也不能把每一篇随笔的链接加入到代码中,使用一个文本保存,获取一个file变量
3、通过python执行系统命令
1 import optparse
2
3 #get the file that user input, return the open file,通过终端输入拿到文件名称并且打开,返回一个file变量
4 def get_file():
5 parser = optparse.OptionParser("usage %prog"+"-f <link_file>") # 运行脚本的格式
6 parser.add_option('-f', dest = 'fname',type = 'string', help = 'specify link file') # 添加运行脚本的变量
7 (options, args) = parser.parse_args() # 把终端获取的变量进行保存,这里不知道怎么解释,有点要意会
8 if options.fname == None: # 文件位置参数不正确,输出使用方法,程序结束
9 print parser.usage
10 file_name = options.fname
11 #file_name = 'test'
12 f = open(file_name,'r')
13 return f
14
15 # execute the shell commands 执行命令,我测试了几种方法
16 #import subprocess
17 import commands,os
18 def execute_shell(s):
19 #obj = subprocess.Popen('wget',shell=True,stdout=subprocess.PIPE)
20 #x = obj.stdout.read() 这是第一种方法,有点问题,因为不熟悉就没有使用
21 shell_command = ' '.join(['wget','-O','x',s]) # 因为wget是下载网页,所以我把每次的结果都写到一个文件里面,这样不会生成很多网页
22 #print(shell_command)
23 os.system(shell_command) # 通过系统执行命令
24 #print(commands.getstatusoutput(shell_command))
25 #(status, result) = commands.getstatusoutput(shell_command) # 这种方法会阻塞,所以也不使用
26 #print(result)
27
28
29
30 import re
31 if __name__ == '__main__':
32 f = get_file()
33 run_num = 0
34 for s in f:
35 #s = re.sub(';','',s)
36 #print(s)
37 execute_shell(s)
38 run_num += 1
39
40 print 'the website is :',run_numView Code