技术标签: python爬虫基础
小白学习:
转:https://zhuanlan.zhihu.com/p/26885412
1.cmd下
scrapy startproject 项目名
2.我一般都是在pycharm中编写代码,所以我会在idea中引入项目,这里不知道如何在pycharm中下载scrapy模块的童鞋,可看我前面的博客:
进入文件下
scrapy genspider 文件名 爬取的网站
scrapy genspider SZtianqi suzhou.tianqi.com
会在文件夹下生成一个SZtianqi的文件
3.编写items.py这个文件,是我们想要封装的名字,在这里面定义
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
#我们将我们需要的名字加进去
class WeatherItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
date=scrapy.Field();#时间
week=scrapy.Field();#日期
img=scrapy.Field();#照片地址
temperature=scrapy.Field();#温度
weather=scrapy.Field();#天气
wind=scrapy.Field();#风速
4.编写SZtianqi.py:作用的从网站上抓取数据,这里和之前的get_html的方法一致,将网页的数据筛取存入item中
# -*- coding: utf-8 -*-
import scrapy
from weather.items import WeatherItem
class SztianqiSpider(scrapy.Spider):
name = "SZtianqi"
# 我们修改一下host,使得Scrapy可以爬取除了苏州之外的天气
allowed_domains = ["tianqi.com"]
# 建立需要爬取信息的url列表
start_urls = []
# 需要爬的城市名称
citys = ['nanjing', 'suzhou', 'shanghai']
# 用一个很简答的循环来生成需要爬的链接:
for city in citys:
start_urls.append('http://' + city + '.tianqi.com')
def parse(self, response):
'''
筛选信息的函数:
date = 今日日期
week = 星期几
img = 表示天气的图标
temperature = 当天的温度
weather = 当天的天气
wind = 当天的风向
'''
# 先建立一个列表,用来保存每天的信息
items = []
# 找到包裹着每天天气信息的div
sixday = response.xpath('//div[@class="tqshow1"]')
# 循环筛选出每天的信息:
for day in sixday:
# 先申请一个weatheritem 的类型来保存结果
item = WeatherItem()
# 观察网页,知道h3标签下的不单单是一行str,我们用trick的方式将它连接起来
date = ''
for datetitle in day.xpath('./h3//text()').extract():
date += datetitle
item['date'] = date
item['week'] = day.xpath('./p//text()').extract()[0]
item['img'] = day.xpath(
'./ul/li[@class="tqpng"]/img/@src').extract()[0]
tq = day.xpath('./ul/li[2]//text()').extract()
# 我们用第二种取巧的方式,将tq里找到的str连接
item['temperature'] = ''.join(tq)
item['weather'] = day.xpath('./ul/li[3]/text()').extract()[0]
item['wind'] = day.xpath('./ul/li[4]/text()').extract()[0]
items.append(item)
return items
这里面的
from weather.items import WeatherItem
是引入items.py的一个类,用与封装的
5.处理封装好的item对象,编写pipelins.py:作用的将数据存入本地或数据库
# -*- coding: utf-8 -*-
import os
import requests
import json
import codecs
import pymysql
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
'''
我们知道,pipelines.py是用来处理收尾爬虫抓到的数据的,
一般情况下,我们会将数据存到本地:
文本形式: 最基本的方式
json格式 :方便其他程序员调用
数据库: 数据量多时
'''
#写入txt文件
class WeatherPipeline(object):
def process_item(self, item, spider):
'''
处理每一个从SZtianqi传过来的
item
'''
#获取当前的工作目录
basc_dir=os.getcwd();
#把文件保存到data目录下
filename=basc_dir+'\\weather\\data\\weather.txt'
#已追加的方式打开文件并写入对应的信息
with open(filename,'a',encoding='utf-8') as f:
f.write(item['date']+'\n')
f.write(item['week']+'\n')
f.write(item['temperature']+'\n')
f.write(item['wind']+'\n')
f.write(item['weather']+'\n')
f.write(item['img']+'\n')
#下载图片
file_img=basc_dir+'\\weather\\data\\image\\'+item['date']+'.png'
with open(file_img,'wb') as f:
f.write(requests.get(item['img']).content)
#print('aaaaaaaaaaaaaaaaaaaaaaaaa')
return item
#写入json文件
class W2json(object):
def process_item(self, item, spider):
#获取本地文件
basc_dir=os.getcwd();
json_dir=basc_dir+'\\weather\\data\\weather.json'
# 打开json文件,向里面以dumps的方式吸入数据
# 注意需要有一个参数ensure_ascii=False ,不然数据会直接为utf编码的方式存入比如:“/xe15”
with codecs.open(json_dir,'a',encoding='utf-8') as f:
line=json.dumps(dict(item),ensure_ascii=False)+'\n'
f.write(line)
return item
#将数据存入数据库
class Rmysql(object):
def process_item(self, item, spider):
#抓取数据存入mysql
#将数据从item中拿出来
date=item['date'];
week=item['week'];
img=item['img']
temperature=item['temperature']
weather=item['weather']
wind=item['wind']
#和本地的数据库连接起来
connection=pymysql.connect(
host='localhost', # 连接的是本地数据库
user='root', # 自己的mysql用户名
passwd='123456', # 自己的密码
db='scrapyDB', # 数据库的名字
charset='utf8mb4', # 默认的编码方式:
cursorclass=pymysql.cursors.DictCursor)
#插库
try:
with connection.cursor() as cursor:
#创建更新数据库的sql
sql="""INSERT INTO WEATHER(date,week,img,temperature,weather,wind)
VALUES (%s, %s,%s,%s,%s,%s)"""
#执行sql
cursor.execute(sql,(date,week,img,temperature,weather,wind))
#提交插入数据
connection.commit()
finally:
#关闭资源 的第二个参数可以将sql缺省语句补全,一般以元组的格式
connection.close()
return item
6.在settings中,调用pipelines的方法
7.执行项目
scrapy crawl SZtianqi
在编写代码是可一边测试一边编写从终端看结果
数据库结果
文章浏览阅读190次。导读:该文是关于静电点电荷论文范文,为你的论文写作提供相关论文资料参考。王静 王亚芳 董爱国 程方锐 张瑞杰 吕砚荻(中国地质大学(北京)物理实验示范中心 北京 100083)摘 要:Matlab是一种功能强大、效率高、便于进行科学和工程计算的交互式软件包.本文使用Matlab软件,给出点电荷和“无限长”直导线,以及同轴圆柱电极产生的静电场的等势线分布图.结果表明利用Matlab软件..._程方锐博士
文章浏览阅读1.5k次。前面跟大家提到过 elementUI验证的问题,那么今天就来看看 点击对话框和关闭按钮 怎么清空验证,清空form表单,避免二次点击还会有 验证错误的提示1、首先在你的对话框 取消按钮 加一个click事件,例如:(ps::callOf里面的addGroupData和ref一 一对应起来)取 消确 定2、点击取消按钮,关闭对话框,清除表单验证callOf(formName){this.creatG..._清除所有elementui form清楚表格交验
文章浏览阅读3.7k次。一开始用localStorage,不论打开多少个页面,哪怕关掉重新打开,同一个网站下的存储的数值还在,问题是,不能同时登录多个账户,以及设置过期时间等后来启用sessionStorage,可以登录多个账户了,页面一关存储的数值也会自动被清掉,不存在安全问题;但来了新的问题,登录后,父页面跳转打开的新页面,两个页面之间的值无法共享了。后来想了一下,可以利用window.opener来解决,自己写..._sessionstorage 不共享
文章浏览阅读1.2k次。我这里用的是idea2019.2的版本第一步:第二步:第三步:第四步:剩下的直接next_idea怎么导入父子结构的maven项目
文章浏览阅读102次。Communication channels are an essential element of every communication system. These channels actually carry the data from one computer to another. There are two categories of communication channels. ..._fiber-optic cable transmits data
文章浏览阅读67次。using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;...
文章浏览阅读3.1k次。win7系统发现桌面右下角网络图标显示红叉或图标正常不能上网,并且打开网络和共享中心显示,依赖的服务或组无法启动,这时候我们需要打开Wlan autoconfig服务。但是在服务项目中找到Wlan autoconfig服务是启用时显示错误代码为1068,怎么才能解决这个问题呢?接下去系统城小编为大家讲解解决方法。1、我们来win7系统的桌面,点击开始在菜单中点击“运行”;2、点击运行弹出来的运行..._win7wlan依赖服务1068错误 csdn
文章浏览阅读400次。附加进程调试_插件附加进程调试的步骤
文章浏览阅读6k次。《java笔试题答案详解[共7页]》由会员分享,可在线阅读,更多相关《java笔试题答案详解[共7页](7页珍藏版)》请在人人文库网上搜索。1、java笔试题以及答案详解 一 一、单项选择题 1Java是从()语言改进重新设计。AAda BC+ CPasacal DBASIC答案:B2下列语句哪一个正确()A Java程序经编译后会产生machine codeB Java程序经编译后会产生byte..._数组是一种对象还是原生类
文章浏览阅读141次。Starting with Oracle9i you have the ability to view the estimated CPU, TEMP and I/O costs for every SQL execution ..._optimizer_cost
文章浏览阅读88次。主机 iprouter 192.168.10.254 192.168.24.254web分发器 192.168.24.1mysql分发器 192.168.24.2web服务器1192.168.24.10web服务器2 192...._keepalive+lvs+mysql+apache+lamp的目的
文章浏览阅读1.4w次,点赞5次,收藏23次。CPC客户端安装经验总结!_cpc客户端