您的位置:首页 > 编程语言 > Python开发

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 正则