这次爬虫作业在端午的时候就想着手进行的,犯拖延症一直没在简书上更新,最近的学习也稍微有点懈怠,一方面是放假的缘故,另一方面跟自身工作时间没能安排出时间进行学习,看书看博客都是碎片化的学习,今天儿童节,及时交作业。
这次爬虫的作业学习:
- MongoDB的一些操作
- 对JS页面的页面处理
- MongoDB Plugin在Pycharm中的使用
查找爬虫入口
构造URL
老规矩chrom 开发者工具 按F12
CTRL+R
查看页面加载,这边需要注意的是Requests headers
里的Referer这个参数,直接访问,如果不加的话会返回403Forbidden
通过多次页面点击发现是JS页面加载
基本URL:
#例子:
http://d1.weather.com.cn/calendar_new/2017/101210101_201706.html?_=1496299957582
#精简:
http://d1.weather.com.cn/calendar_new/{1}/101210101_2017{2}.html.format(str(year),str(month))
解析返回数据
返回的数据格式不是json格式,是类似json的字典列表字符串,需要做字符串切片处理、序列化之后重构字典,最后插入MongoDB
代码
# -*- coding:utf-8 -*-
import sys
import json
import requests
import pymongo
from pymongo import MongoClient
reload(sys)
sys.path.append('..')
sys.setdefaultencoding('utf-8')
class chinaweather(object):
def __init__(self):
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection':'keep-alive',
'Host':'d1.weather.com.cn',
'Referer':'http://www.weather.com.cn/weather40d/101210101.shtml',
'Cookie': 'vjuids=-35cf735ec.15c3a674e60.0.ea0c2b4b0db22; f_city=%E5%8C%97%E4%BA%AC%7C101010100%7C; BIGipServerd1src_pool=1874396221.20480.0000; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1495628468,1495628495,1495642584; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1495642621; vjlast=1495628468.1495642583.13'
}
self.headers = headers
self.base_url = 'http://d1.weather.com.cn/calendar_new/2016/101210101_2016%s.html'
def request_html_data(self, url):
html = requests.get(url, headers=self.headers).content
html = html.decode()
#字符串切片,去除"var fc40 ="
html_json = json.loads(html[11:])
weather_list = []
for weather in html_json:
item = {}
item['日期'] = weather.get('date')
item['降水概率'] = weather.get('hgl')
item['最高温度'] = weather.get('hmax')
item['最低温度'] = weather.get('hmin')
item['农历日期'] = weather.get('nlyf') + weather.get('nl')
item['不宜'] = weather.get('alins')
item['宜'] = weather.get('als')
weather_list.append(item)
#数据存储mongodb
client = MongoClient('mongodb://172.16.110.163:27017/')
db = client['weather']
posts = db.weather
#插入含多字典列表
posts.insert_many(weather_list)
if __name__ == '__main__':
cw = chinaweather()
for i in range(1, 13):
#拼接字符串,月份小于10,需要加0
if i < 10:
str_i = "0" + str(i)
url = cw.base_url % str_i
cw.request_html_data(url)
else:
str_i = str(i)
url = cw.base_url % str_i
cw.request_html_data(url)
MongoDB存储数据
用MongoDB存这样的数据太方便了,不必想Mysql中那样创建表、定义表结构 字段类型,直接可以插入数据
参考资料
mongodb 在pycharm插件安装步骤
How To Install MongoDB on CentOS 7