很多网站都提供了浏览者本地的天气信息,这些信息是如何获取到的呢,方法有很多种,大多是利用某些网站提供的天气api获取的,也有利用爬虫采集的。本文就介绍如何用Scrapy来采集天气信息(从新浪天气频道采集:?)。
先上一张最终的效果截图:
安装 scrapy-0.24:
完成这步后,可以用下面的命令测试一下安装是否正确:
如果正常,效果如图所示:
在开始爬取之前,必须创建一个新的Scrapy项目。进入您打算存储代码的目录中,运行下列命令:
如果正常,效果如图所示:
这些文件分别是:
- scrapy.cfg: 项目的配置文件
- weather/: 该项目的python模块。之后将在此加入代码。
- weather/items.py: 项目中的item文件.
- weather/pipelines.py: 项目中的pipelines文件.
- weather/settings.py: 项目的设置文件.
- weather/spiders/: 放置spider代码的目录.
Item 是保存爬取到的数据的容器;其使用方法和python字典类似,并且提供了额外保护机制来避免拼写错误导致的未定义字段错误。
首先根据需要从weather.sina.com.cn获取到的数据对item进行建模。 我们需要从weather.sina.com.cn中获取当前城市名,后续9天的日期,天气描述和温度等信息。对此,在item中定义相应的字段。编辑 weather 目录中的 items.py 文件:
<span style="color: #008000;"># <span style="color: #008000;"> Define here the models for your scraped items<span style="color: #008000;">
<span style="color: #008000;"> See documentation in:<span style="color: #008000;">
<span style="color: #008000;"> http://doc.scrapy.org/en/latest/topics/items.html
<span style="color: #0000ff;">import<span style="color: #000000;"> scrapy
<span style="color: #0000ff;">class<span style="color: #000000;"> WeatherItem(scrapy.Item):
<span style="color: #008000;">#<span style="color: #008000;"> define the fields for your item here like:
<span style="color: #008000;">#<span style="color: #008000;"> name = scrapy.Field()
<span style="color: #008000;">#<span style="color: #008000;"> demo 1
city =<span style="color: #000000;"> scrapy.Field()
date =<span style="color: #000000;"> scrapy.Field()
dayDesc =<span style="color: #000000;"> scrapy.Field()
dayTemp =<span style="color: #000000;"> scrapy.Field()
<span style="color: #0000ff;">pass
<h3 id="4-spider-">4. 编写获取天气数据的爬虫(Spider)
Spider是用户编写用于从单个网站(或者一些网站)爬取数据的类。
其包含了一个用于下载的初始URL,如何跟进网页中的链接以及如何分析页面中的内容, 提取生成 item 的方法。
为了创建一个Spider,必须继承 scrapy.Spider 类, 且定义以下三个属性:
-
name: 用于区别Spider。该名字必须是唯一的,您不可以为不同的Spider设定相同的名字。
-
start_urls: 包含了Spider在启动时进行爬取的url列表。因此,第一个被获取到的页面将是其中之一。后续的URL则从初始的URL获取到的数据中提取。
-
parse() 是spider的一个方法。 被调用时,每个初始URL完成下载后生成的 Response 对象将会作为唯一的参数传递给该函数。 该方法负责解析返回的数据(response data),提取数据(生成item)以及生成需要进一步处理的URL的 Request 对象。
我们通过浏览器的查看源码工具先来分析一下需要获取的数据网源代码:
武汉
01-28
今天
白天
夜间
1°C / -2°C
北风 3~4级
无持续风向 小于3级
01-29
星期四
白天
夜间
1°C / -2°C
无持续风向 小于3级
我们可以看到:
- 城市名可以通过获取id为slider_ct_name的h4元素获取
- 日期可以通过获取id为blk_fc_c0_scroll下的class为wt_fc_c0_i_date的p元素获取
- 天气描述可以通过获取id为blk_fc_c0_scroll下的class为icons0_wt的img元素获取
- 温度可以通过获取id为blk_fc_c0_scroll下的class为wt_fc_c0_i_temp的p元素获取
因此,我们的Spider代码如下,保存在 weather/spiders 目录下的 localweather.py 文件中:
weather.items <span style="color: #0000ff;">class<span style="color: #000000;"> WeatherSpider(scrapy.Spider):
name = <span style="color: #800000;">"<span style="color: #800000;">myweather<span style="color: #800000;">"<span style="color: #000000;">
allowed_domains = [<span style="color: #800000;">"<span style="color: #800000;">sina.com.cn<span style="color: #800000;">"<span style="color: #000000;">]
start_urls = [<span style="color: #800000;">'<span style="color: #800000;">http://weather.sina.com.cn<span style="color: #800000;">'<span style="color: #000000;">]
</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> parse(self,response):
item </span>=<span style="color: #000000;"> WeatherItem()
item[</span><span style="color: #800000;">'</span><span style="color: #800000;">city</span><span style="color: #800000;">'</span>] = response.xpath(<span style="color: #800000;">'</span><span style="color: #800000;">//*[@id="slider_ct_name"]/text()</span><span style="color: #800000;">'</span><span style="color: #000000;">).extract()
tenDay </span>= response.xpath(<span style="color: #800000;">'</span><span style="color: #800000;">//*[@id="blk_fc_c0_scroll"]</span><span style="color: #800000;">'</span><span style="color: #000000;">);
item[</span><span style="color: #800000;">'</span><span style="color: #800000;">date</span><span style="color: #800000;">'</span>] = tenDay.css(<span style="color: #800000;">'</span><span style="color: #800000;">p.wt_fc_c0_i_date::text</span><span style="color: #800000;">'</span><span style="color: #000000;">).extract()
item[</span><span style="color: #800000;">'</span><span style="color: #800000;">dayDesc</span><span style="color: #800000;">'</span>] = tenDay.css(<span style="color: #800000;">'</span><span style="color: #800000;">img.icons0_wt::attr(title)</span><span style="color: #800000;">'</span><span style="color: #000000;">).extract()
item[</span><span style="color: #800000;">'</span><span style="color: #800000;">dayTemp</span><span style="color: #800000;">'</span>] = tenDay.css(<span style="color: #800000;">'</span><span style="color: #800000;">p.wt_fc_c0_i_temp::text</span><span style="color: #800000;">'</span><span style="color: #000000;">).extract()
</span><span style="color: #0000ff;">return</span> item</pre>
到这里为止,我们需要验证一下爬虫是否能正常工作(即能否取到我们想要的数据),验证的方法就是在命令行(重要:在项目的scrapy.cfg文件同级目录运行命令,下同)中运行下面的代码:
这行命令的意思是,运行名字为 myweather 的爬虫(我们在上一步中定义的),然后把结果以json格式保存在wea.json文件中。命令运行结果如下:
然后,我们查看当前目录下的wea.json文件,正常情况下效果如下:
我们看到,wea.json中已经有数据了,只是数据是以unicode方式编码的。
上面只是把数据保存在json文件中了,如果我们想自己保存在文件或数据库中,如何操作呢?
这里就要用到 Item Pipeline 了,那么 Item Pipeline 是什么呢?
当Item在Spider中被收集之后,它将会被传递到Item Pipeline中,一些组件会按照一定的顺序执行对Item的处理。
每个item pipeline组件(有时称之为“Item Pipeline”)是实现了简单方法的Python类。他们接收到Item并通过它执行一些行为,同时也决定此Item是否继续通过pipeline,或是被丢弃而不再进行处理。
item pipeline的典型应用有:
- 清理HTML数据
- 验证爬取的数据(检查item包含某些字段)
- 查重(并丢弃)
- 将爬取结果保存到文件或数据库中
每个item pipeline组件都需要调用 process_item 方法,这个方法必须返回一个 Item (或任何继承类)对象, 或是抛出 DropItem异常,被丢弃的item将不会被之后的pipeline组件所处理。
我们这里把数据转码后保存在 wea.txt 文本中。
pipelines.py文件在创建项目时已经自动被创建好了,我们在其中加上保存到文件的代码:
<span style="color: #008000;"># <span style="color: #008000;"> Define your item pipelines here<span style="color: #008000;">
<span style="color: #008000;"> Don't forget to add your pipeline to the ITEM_PIPELINES setting<span style="color: #008000;">
<span style="color: #008000;"> See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
<span style="color: #0000ff;">class<span style="color: #000000;"> WeatherPipeline(object):
<span style="color: #0000ff;">def <span style="color: #800080;">init<span style="color: #000000;">(self):
self.file = open(<span style="color: #800000;">'<span style="color: #800000;">wea.txt<span style="color: #800000;">',<span style="color: #800000;">'<span style="color: #800000;">w+<span style="color: #800000;">'<span style="color: #000000;">)
</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> process_item(self,item,spider):
city </span>= item[<span style="color: #800000;">'</span><span style="color: #800000;">city</span><span style="color: #800000;">'</span>][0].encode(<span style="color: #800000;">'</span><span style="color: #800000;">utf-8</span><span style="color: #800000;">'</span><span style="color: #000000;">)
self.file.write(</span><span style="color: #800000;">'</span><span style="color: #800000;">city:</span><span style="color: #800000;">'</span> + str(city) + <span style="color: #800000;">'</span><span style="color: #800000;">nn</span><span style="color: #800000;">'</span><span style="color: #000000;">)
date </span>= item[<span style="color: #800000;">'</span><span style="color: #800000;">date</span><span style="color: #800000;">'</span><span style="color: #000000;">]
desc </span>= item[<span style="color: #800000;">'</span><span style="color: #800000;">dayDesc</span><span style="color: #800000;">'</span><span style="color: #000000;">]
dayDesc </span>= desc[1::2<span style="color: #000000;">]
nightDesc </span>= desc[0::2<span style="color: #000000;">]
dayTemp </span>= item[<span style="color: #800000;">'</span><span style="color: #800000;">dayTemp</span><span style="color: #800000;">'</span><span style="color: #000000;">]
weaitem </span>=<span style="color: #000000;"> zip(date,dayDesc,nightDesc,dayTemp)
</span><span style="color: #0000ff;">for</span> i <span style="color: #0000ff;">in</span><span style="color: #000000;"> range(len(weaitem)):
item </span>=<span style="color: #000000;"> weaitem[i]
d </span>=<span style="color: #000000;"> item[0]
dd </span>= item[1<span style="color: #000000;">]
nd </span>= item[2<span style="color: #000000;">]
ta </span>= item[3].split(<span style="color: #800000;">'</span><span style="color: #800000;">/</span><span style="color: #800000;">'</span><span style="color: #000000;">)
dt </span>=<span style="color: #000000;"> ta[0]
nt </span>= ta[1<span style="color: #000000;">]
txt </span>= <span style="color: #800000;">'</span><span style="color: #800000;">date:{0}ttday:{1}({2})ttnight:{3}({4})nn</span><span style="color: #800000;">'</span><span style="color: #000000;">.format(
d,dd.encode(</span><span style="color: #800000;">'</span><span style="color: #800000;">utf-8</span><span style="color: #800000;">'</span><span style="color: #000000;">),dt.encode(</span><span style="color: #800000;">'</span><span style="color: #800000;">utf-8</span><span style="color: #800000;">'</span><span style="color: #000000;">),nd.encode(</span><span style="color: #800000;">'</span><span style="color: #800000;">utf-8</span><span style="color: #800000;">'</span><span style="color: #000000;">),nt.encode(</span><span style="color: #800000;">'</span><span style="color: #800000;">utf-8</span><span style="color: #800000;">'</span><span style="color: #000000;">)
)
self.file.write(txt)
</span><span style="color: #0000ff;">return</span> item</pre>
代码比较简单,都是python比较基础的语法,如果您感觉比较吃力,建议先去学一下python基础课。
写好ITEM_PIPELINES后,还有很重要的一步,就是把 ITEM_PIPELINES 添加到设置文件 settings.py 中。
ITEM_PIPELINES =: 1
另外,有些网站对网络爬虫进行了阻止(注:本项目仅从技术角度处理此问题,个人强烈不建议您用爬虫爬取有版权信息的数据),我们可以在设置中修改一下爬虫的 USER_AGENT 和 Referer 信息,增加爬虫请求的时间间隔。
整个 settings.py 文件内容如下:
<span style="color: #008000;"># <span style="color: #008000;"> Scrapy settings for weather project<span style="color: #008000;">
<span style="color: #008000;"> For simplicity,this file contains only the most important settings by<span style="color: #008000;">
<span style="color: #008000;"> default. All the other settings are documented here:<span style="color: #008000;">
<span style="color: #008000;"> http://doc.scrapy.org/en/latest/topics/settings.html<span style="color: #008000;">
<span style="color: #000000;">
BOT_NAME = <span style="color: #800000;">'<span style="color: #800000;">Googlebot<span style="color: #800000;">'<span style="color: #000000;">
SPIDER_MODULES = [<span style="color: #800000;">'<span style="color: #800000;">weather.spiders<span style="color: #800000;">'<span style="color: #000000;">]
NEWSPIDER_MODULE = <span style="color: #800000;">'<span style="color: #800000;">weather.spiders<span style="color: #800000;">'
<span style="color: #008000;">#<span style="color: #008000;"> Crawl responsibly by identifying yourself (and your website) on the user-agent<span style="color: #008000;">
<span style="color: #008000;">USER_AGENT = 'weather (+http://www.yourdomain.com)'
USER_AGENT = <span style="color: #800000;">'<span style="color: #800000;">User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/39.0.2171.95 Safari/537.36<span style="color: #800000;">'<span style="color: #000000;">
DEFAULT_REQUEST_HEADERS =<span style="color: #000000;"> {
<span style="color: #800000;">'<span style="color: #800000;">Referer<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">http://www.weibo.com<span style="color: #800000;">'<span style="color: #000000;">
}
ITEM_PIPELINES =<span style="color: #000000;"> {
<span style="color: #800000;">'<span style="color: #800000;">weather.pipelines.WeatherPipeline<span style="color: #800000;">': 1<span style="color: #000000;">
}
DOWNLOAD_DELAY = 0.5
在项目的scrapy.cfg同级目录下用下面的命令运行爬虫:
$ scrapy crawl myweather
然后,在当前目录下会多一个 wea.txt 文件,内容如下:
到此我们基于scrapy的天气数据采集就完成了。
最近看到有朋友反馈代码按课程运行后,最后的数据中只有城市数据,没有天气数据,我检查了一下代码,找到了问题存在的原因。
scrapy内置的html解析是基于lxml库的,这个库对html的解析的容错性不是很好,通过检查虚拟机中获取到的网页源码,发现有部分标签是不匹配的(地区和浏览器不同取到的源码可能不同),检查结果如图:
所以导致在spider中取到的日期数据(item['date'])为空,然后在pilepine代码中做zip操作后,整个 weaitem 为空,所以最终只有城市数据了。
既然找到了原因,我们换个html代码解析器就可以了,这里建议用 BeautifulSoup (官网:?),这个解析器有比较好的容错能力,具体用法可以参考上面的文档。
BeautifulSoup安装:
http:
-zxvf beautifulsoup4-..安装
$ cd beautifulsoup4 -<span style="color: #800080;">4.3.<span style="color: #800080;">2<span style="color: #000000;">
$ <span style="color: #0000ff;">sudo python setup.py <span style="color: #0000ff;">install
bs4 weather.items <span style="color: #0000ff;">class<span style="color: #000000;"> WeatherSpider(scrapy.Spider):
name = <span style="color: #800000;">"<span style="color: #800000;">myweather<span style="color: #800000;">"<span style="color: #000000;">
allowed_domains = [<span style="color: #800000;">"<span style="color: #800000;">sina.com.cn<span style="color: #800000;">"<span style="color: #000000;">]
start_urls = [<span style="color: #800000;">'<span style="color: #800000;">http://weather.sina.com.cn<span style="color: #800000;">'<span style="color: #000000;">]
</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> parse(self,response):
html_doc </span>=<span style="color: #000000;"> response.body
</span><span style="color: #008000;">#</span><span style="color: #008000;">html_doc = html_doc.decode('utf-8')</span>
soup =<span style="color: #000000;"> BeautifulSoup(html_doc)
itemTemp </span>=<span style="color: #000000;"> {}
itemTemp[</span><span style="color: #800000;">'</span><span style="color: #800000;">city</span><span style="color: #800000;">'</span>] = soup.find(id=<span style="color: #800000;">'</span><span style="color: #800000;">slider_ct_name</span><span style="color: #800000;">'</span><span style="color: #000000;">)
tenDay </span>= soup.find(id=<span style="color: #800000;">'</span><span style="color: #800000;">blk_fc_c0_scroll</span><span style="color: #800000;">'</span><span style="color: #000000;">)
itemTemp[</span><span style="color: #800000;">'</span><span style="color: #800000;">date</span><span style="color: #800000;">'</span>] = tenDay.findAll(<span style="color: #800000;">"</span><span style="color: #800000;">p</span><span style="color: #800000;">"</span>,{<span style="color: #800000;">"</span><span style="color: #800000;">class</span><span style="color: #800000;">"</span>: <span style="color: #800000;">'</span><span style="color: #800000;">wt_fc_c0_i_date</span><span style="color: #800000;">'</span><span style="color: #000000;">})
itemTemp[</span><span style="color: #800000;">'</span><span style="color: #800000;">dayDesc</span><span style="color: #800000;">'</span>] = tenDay.findAll(<span style="color: #800000;">"</span><span style="color: #800000;">img</span><span style="color: #800000;">"</span>,{<span style="color: #800000;">"</span><span style="color: #800000;">class</span><span style="color: #800000;">"</span>: <span style="color: #800000;">'</span><span style="color: #800000;">icons0_wt</span><span style="color: #800000;">'</span><span style="color: #000000;">})
itemTemp[</span><span style="color: #800000;">'</span><span style="color: #800000;">dayTemp</span><span style="color: #800000;">'</span>] = tenDay.findAll(<span style="color: #800000;">'</span><span style="color: #800000;">p</span><span style="color: #800000;">'</span>,{<span style="color: #800000;">"</span><span style="color: #800000;">class</span><span style="color: #800000;">"</span>: <span style="color: #800000;">'</span><span style="color: #800000;">wt_fc_c0_i_temp</span><span style="color: #800000;">'</span><span style="color: #000000;">})
item </span>=<span style="color: #000000;"> WeatherItem()
</span><span style="color: #0000ff;">for</span> att <span style="color: #0000ff;">in</span><span style="color: #000000;"> itemTemp:
item[att] </span>=<span style="color: #000000;"> []
</span><span style="color: #0000ff;">if</span> att == <span style="color: #800000;">'</span><span style="color: #800000;">city</span><span style="color: #800000;">'</span><span style="color: #000000;">:
item[att] </span>=<span style="color: #000000;"> itemTemp.get(att).text
</span><span style="color: #0000ff;">continue</span>
<span style="color: #0000ff;">for</span> obj <span style="color: #0000ff;">in</span><span style="color: #000000;"> itemTemp.get(att):
</span><span style="color: #0000ff;">if</span> att == <span style="color: #800000;">'</span><span style="color: #800000;">dayDesc</span><span style="color: #800000;">'</span><span style="color: #000000;">:
item[att].append(obj[</span><span style="color: #800000;">'</span><span style="color: #800000;">title</span><span style="color: #800000;">'</span><span style="color: #000000;">])
</span><span style="color: #0000ff;">else</span><span style="color: #000000;">:
item[att].append(obj.text)
</span><span style="color: #0000ff;">return</span> item</pre>
$ scrapy crawl myweather
如果是晚上运行爬虫,当天的白天天气是没有的(已经过去了),针对这部分建议自己优化。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|