程序员大数据 爬虫Python AI Sql

Scrapy学习(一)-爬取天气信息

2017-08-23  本文已影响0人  Fitz916

开始学习下scrapy这个爬虫框架,安装过程可以随便google,这里不再赘述

scrapy文档 这里面有个入门教程可以参考
今天示例网站用的是之前的天气查询。将它改成用scrapy来爬取

image.png

创建项目

│  scrapy.cfg
│
└─scrapy_weather
    │  items.py
    │  middlewares.py
    │  pipelines.py
    │  settings.py
    │  __init__.py
    │
    ├─spiders
        │  __init__.py

定义item

import scrapy

class ScrapyWeatherItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    date = scrapy.Field()
    title = scrapy.Field()
    tem = scrapy.Field()
    win = scrapy.Field()
    win_lv = scrapy.Field()
    pass

编写爬虫

import scrapy
from scrapy_weather.items import ScrapyWeatherItem
from bs4 import BeautifulSoup

class WeatherSoider(scrapy.Spider):
    # name:用于区别Spider。该名字必须是唯一的
    name = 'weather'
    # 可选。包含了spider允许爬取的域名(domain)列表(list)。 当 OffsiteMiddleware 启用时, 域名不在列表中的URL不会被跟进
    allowed_domains = ['weather.com.cn']
    # start_urls:包含了Spider在启动时进行爬取的url列表。
    # 因此,第一个被获取到的页面将是其中之一。后续的URL则从初始的URL获取到的数据中提取
    start_urls = [
        "http://www.weather.com.cn/weather/101010100.shtml",
        "http://www.weather.com.cn/weather/101020100.shtml",
        "http://www.weather.com.cn/weather/101210101.shtml",
    ]
    #parse()是spider的一个方法。被调用时,每个初始URL完成下载后生成的Response对象将会作为唯一的参数传递给该函数。
    # 该方法负责解析返回的数据(responsedata),提取数据

    def parse(self, response):
        item = ScrapyWeatherItem()
        html = response.body
        soup = BeautifulSoup(html, 'html.parser')
        data = soup.find("div", {'id': '7d'})
        wea = {}
        wea['date'] = data.find_all('h1')
        wea['title'] = data.find_all('p',{'class': 'wea'} )
        wea['tem'] = data.find_all('p', {'class': 'tem'})
        wea['win'] = data.find_all('p', {'class': 'win'})
        for w in wea:
            item[w] = []
            for o in wea.get(w):
                if w == 'date':
                    item[w].append(o.get_text())
                elif w == 'title':
                    item[w].append(o['title'])
                elif w == 'win':
                    win1 = o.find('span')['title']
                    win2 = o.find('span').find_next()['title']
                    win_lv = o.i.get_text()
                    item[w].append('%s %s %s' % (win1, win2, win_lv))
                elif w == 'tem':
                    high = o.find('span').get_text()
                    lower = o.find('i').get_text()
                    item[w].append('最高温:%s,最低温:%s' %(high, lower))
        return item

处理爬取到的数据

上一步爬虫的item会返回到Pipeline中,所以我们在这里处理数据即可,这一步也可以省略,只要在运行命令后加个-o weather.json,这样也可以将数据保存到这个json文件中

# spider中抓取的数据会返回到这里,我们可以在这里对数据进行保存到文件,数据库等操作
import codecs

class ScrapyWeatherPipeline(object):

    def __init__(self):
        self.file = codecs.open('G:/python/weather.xml', 'w', encoding='utf-8')  # 初始化一个weather.xml的文件
  
    def process_item(self, item, spider):
        for i in range(0,7):
            s = ''
            for sub in item:
                s += item[sub][i] + ' '
            self.file.write(s+'\n')
            if i == 6:
                self.file.write('\n')
        return item

最后可以在settings.py中设置一些东西,比如robots.txt具体我还没仔细看

运行

上一篇 下一篇

猜你喜欢

热点阅读