python抓取动态网页(就是一个解析xml和html之类的库,用着还算顺手 )
优采云 发布时间: 2021-10-15 20:08python抓取动态网页(就是一个解析xml和html之类的库,用着还算顺手
)
Beautiful Soup 是一个 Python 库,专为快速周转项目(如屏幕抓取)而设计。总之就是一个解析xml和html的库,使用起来还算流畅。
官网地址:
下面介绍一下使用python和Beautiful Soup捕获网页PM2.5数据。
PM2.5 网站 的数据:
这个网站上有对应的PM2.5数据。他们在几个地方布置了监视器,大约每小时更新一次(有时仪器数据会丢失)。我们要捕捉的数据是几个监测点的一些空气质量指标。
1 def getPM25():
2 url = "http://www.pm25.com/city/wuhan.html"
3
4 headers = {
5 "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
6 "Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
7 "Connection":"keep-alive",
8 "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0",
9 }
10 try:
11 req = urllib2.Request(url,headers=headers)
12 response = urllib2.urlopen(req)
13 content = response.read()
14 response.close()
15 pm = BSoup(content,from_encoding="utf-8")
16 logging.info(pm.select(".citydata_updatetime")[0].get_text() + u" ")
17 with open('pm2dot5.txt','a') as f:
18 print>>f, pm.select(".citydata_updatetime")[0].get_text()
19 for locate in pm.select(".pj_area_data ul:nth-of-type(1) li"):
20 print>>f, locate.select(".pjadt_location")[0].get_text().rjust(15),"\t",\
21 locate.select(".pjadt_aqi")[0].get_text().rjust(15),"\t",\
22 locate.select(".pjadt_quality")[0].get_text().rjust(15),"\t",\
23 locate.select(".pjadt_wuranwu")[0].get_text().rjust(15),"\t",\
24 locate.select(".pjadt_pm25")[0].get_text().rjust(15),"\t",\
25 locate.select(".pjadt_pm10")[0].get_text().rjust(15)
26 print>>f, "\n\n\n"
27 return 0
28 except Exception,e:
29 logging.error(e)
30 return 1
主要使用python的库urllib2
提取标签内容
下面是使用Beautiful Soup解析html内容并提取标签中的值。具体功能请参考官方文档。
这里主要使用select方法和get_text方法。
select方法可以根据标签名称(标签,如a、li、body)或css类或id来选择元素。
get_text 方法可以获取对应的文本,比如“hello”,可以获取到“hello”
具体元素类型需要借助浏览器的评论元素功能查看
写文字:
主要使用python的with语法,with可以保证在发生异常时关闭打开的文件。同时使用了流重定向的一个小技巧,
print >> f, "hello" f 是打开的文件流。这句话的意思是将print打印的东西重定向到文件中。
日志记录:
由于这个程序需要长时间在后台运行,所以最好记录下错误信息,方便调试。使用python自带的日志模块。
1 logging.basicConfig(level=logging.DEBUG,
2 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
3 datefmt='%a, %d %b %Y %H:%M:%S',
4 filename='debug.log',
5 filemode='w')
6 console = logging.StreamHandler()
7 console.setLevel(logging.INFO)
8 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
9 console.setFormatter(formatter)
10 logging.getLogger('').addHandler(console)
11 Rthandler = RotatingFileHandler('debug.log', maxBytes=1*1024*1024,backupCount=5)
12 Rthandler.setLevel(logging.INFO)
13 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
14 Rthandler.setFormatter(formatter)
15 logging.getLogger('').addHandler(Rthandler)
这包括一些,设置日志的格式,以及日志文件的最大大小。
定时操作:
定时运行,可以在每天指定时间捕获PM2.5数据,并结合卫星通过时间做进一步分析。python自带的sched模块也经常使用。
1 def run():
2 while True:
3 s = sched.scheduler(time.time, time.sleep)
4 s.enterabs(each_day_time(9,50,30), 1, getPM25, ())
5 try:
6 s.run()
7 except:
8 s.run()
9 time.sleep(60*60)
10 logging.info("second run")
11 while getPM25():
12 pass
13 time.sleep( 60*60)
14 logging.info("third run")
15 while getPM25():
16 pass
17 time.sleep(60*60)
18 logging.info("fourth run")
19 while getPM25():
20 pass
21 logging.info(u"\n\n等待下次运行...")
其中 each_day_time 是获取指定时间的函数
1 def each_day_time(hour,minute,sec):
2 today = datetime.datetime.today()
3 today = datetime.datetime(today.year,today.month,today.day,hour,minute,sec)
4 tomorrow = today + datetime.timedelta(days=1)
5 xtime = time.mktime(tomorrow.timetuple())
6 #xtime = time.mktime(today.timetuple())
7 return xtime
此外,如果指定的时间已过,他将继续运行。
下载完整代码(python 2.7):
另:直接双击pyw文件,会调用pythonw.exe执行,如果没有GUI,默认是后台运行。
获取的结果: