python 抓取天气时碰到的一点正则问题 (.*)和(.*?)
2015-08-01 10:50
656 查看
#coding=utf-8 import urllib2 import urllib import re city_number=101191101 url='http://www.weather.com.cn/weather/'+str(city_number)+'.shtml' req=urllib2.Request(url) response=urllib2.urlopen(req) myPage=response.read() pattern=re.compile("<li class='dn' data-dn='7d2'>([\s\S]*?)</li>") myMatch=pattern.search(myPage,re.S) sa=myMatch.group(1) BgnPartRex = re.compile("\"") sa=BgnPartRex.sub("",sa) #print sa temperature=re.compile('<span>(.*?)</span><i>') temp=temperature.findall(sa,re.S) print temp
第18行正则中用(.*?)和(.*)的结果一样,先看页面源码:
<h1>明天</h1>
<h2>2日</h2>
<big class=jpg50 d00></big>
<big class=jpg50 n00></big>
<p class=wea>晴</p>
<p class=tem tem1>
<span>37</span><i>°C</i>
</p>
<p class=tem tem2>
<span>28</span><i>°C</i>
</p>
<p class=win>
<em>
<span title=南风 class=S></span>
<span title=南风 class=S></span>
</em>
<i>3-4级转4-5级</i>
</p>
<div class=slid></div>
其中代表温度的两行形式一样,因此使用 (.*?) 匹配到第一行,再通过findall方法把第二行也匹配了出来,而使用(.*)不能匹配换行,所以同样只能匹配到第一行,因而效果与(.*?)相同。千万要记住(.*)不能匹配换行,如果想要匹配换行,应使用([\s\S]*)。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Java简单字符串插值实现
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法