问题背景:需要统计雁门关10年的客流量数据,每次需要选择时间,然后提交,网页上回返回客流量数据, 网址链接:http://www./yuce/index/cid/166.shtml 思路:网页选择时间,然后提交时间,页面返回一个数据,和工作上遇到的POST类似,考虑通过python编写一个post循环得到相应的数据并保存到excel。 步骤: 1、在chrome打开网页,F12进入调试状态 选择network找到Form Data就是每次post给后台服务器的数据,可以发现post的data有时间date和dosubmit信息。 2、python脚本编写 # coding=utf-8 import requests import datetime post_url = 'http://www./yuce/index/cid/166.shtml' # 现在的时间 now = datetime.datetime.now() # 递减的时间 delta = datetime.timedelta(days=-1) # 10年后的时间 endnow = now - datetime.timedelta(days=3662) # 10年后的时间转换成字符串 endnow = str(endnow.strftime('%Y-%m-%d')) offset = now csvfile = open('output.csv', 'w') # 创建记录信息 csvfile.write('时间' ',') csvfile.write('人数' '\n') # 当日期减少到10年后的日期,循环结束 while str(offset.strftime('%Y-%m-%d')) != endnow: offset = delta data = { 'date': str(offset.strftime('%Y-%m-%d')), 'dosubmit': '查询 '} tqHtml = requests.post(post_url, data=data) res = tqHtml.text num = res[10300:10400].split('<')[0] print('统计到' str(offset.strftime('%Y-%m-%d')) '的来访客流量') csvfile.write(str(offset.strftime('%Y-%m-%d')) ',') csvfile.write(num '\n') 代码中首先计算了10年的时间天数为3662,达到对应的时间字符串,爬虫的数据放在csv文件中。通过requests模块进行post,返回的html文件,尝试了json等方式都无法提取到相应的客流量数据,最后采用了字符串的处理方法,通过split解析出了相应的人数信息。 |
|