Python学习日记 Scrapy框架 2. 爬取教师信息
1. 创建新项目
Terminal中进入待创建项目目录,输入scrapy startproject 项目名称
出现问题:
解决办法:在Terminal输入 pip install -I cryptography,等待其安装成功。然后再输入scrapy startproject Spider(自定义的项目名)即可创建成功。
出现如上后创建成功。
项目中会得到的文件结构如下:
scrapy.cfg :Scrapy的配置未见
items.py :Items定义爬取的数据结构(待爬取的内容格式)
middlewares.py :Middlewares定义爬取的中间件
pipelines.py:Pipelines定义数据管道(储存内容)
settings.py:配置文件
2.明确爬取内容,编写items.py
该项目预期爬取教师信息,则有老师姓名、职位、简介
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ItcastspiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# 老师姓名
name = scrapy.Field()
# 职位
level = scrapy.Field()
# 介绍信息
info = scrapy.Field()
3. 编写爬虫文件
3.1 获取相应
首先通过 scrapy shell example.com,response通过最简单的方法得到相应。如果是403代表爬虫被封了;如果是200代表访问正常。所以我们需要设置user-agent,伪装成浏览器:scrapy shell example.com -s USER_AGENT。
3.2 创建爬虫文件
根据创建项目时scrapy startproject xx时应答:
You can start your first spider with:
cd XX
scrapy gensipder example example.com
上述中,example:爬虫名,不可与项目名重复;example.com:爬虫范围,即www.baidu.com后爬虫不会在www.google.com上爬取内容。
3.3 Xpath语法
符号 | 作用 |
/ | 选择某个标签下的所有内容 |
text() | 选择标签内所包含的文本 |
@ | 选择标签属性信息 |
// | 选择所有标签 |
[@属性=值] | 该标签属性满足一定条件 |
在网页中F12打开开发者工具,定位需要爬取的信息后,通过Copy xpath获得对应的xpath的表达式,在prase函数中编写数据定位代码。
先锁定需要爬取信息,然后通过Copy xpath获取xpath表达式,比如我们需要获得该图左边人物的名字和职称
/html/body/div[5]/div/ul/li[1]/div[2]
/html/body/div[5]/div/ul/li[1]/div[2]/p[1]/b
/html/body/div[5]/div/ul/li[1]/div[2]/p[1]/text()
上述三个表达式分别表示文字栏目录,名字,职位。通过在scrapy shell XX得到响应后调试,可以得:
在定位完成需要爬取的信息后,开始编写爬虫文件。
# -*- coding: utf-8 -*-
import scrapy
from new2.items import New2Item
class ItcastSpider(scrapy.Spider):
name = 'itcast' # 爬虫名
allowed_domains = ['me.sjtu.edu.cn'] #允许爬虫范围
start_urls = ['http://me.sjtu.edu.cn/academician.html'] #第一个爬取url
def parse(self, response):
# 通过scrapy内置的xpath规则解析网页,返回一个包含selector对象的列表
teacher_list = response.xpath('//div[@class="txtk"]')
# 实例化类
item = New2Item()
for each in teacher_list:
item['name'] = each.xpath('./p/b').extract()[0]
item['level'] = each.xpath('./p/text()').extract()[0]
item['info'] = each.xpath('./div/p/span').extract()[0]
yield item
4. 编写管道文件
管道文件pipelines的作用是将爬取内容保存到本地
# -*- coding: utf-8 -*-
# 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
import json
class New2Pipeline(object):
def __init__(self):
# 在本地创建teacher.json文件
self.filename = open('teacher.json', 'wb+')
def process_item(self, item, spider):
# python类型转化为json字符串
text = json.dumps(dict(item), ensure_ascii=False) + '\n'
# 写入
self.filename.write(text.encode('utf-8'))
return item
5. Setting文件
这里原本注释状态需要取消,不然无法运行。
6. 运行
在目录下,输入scrapy crawl itcast
笔者初学python、爬虫,欢迎交流,批评,谢谢各位大佬。
参考
https://www.cnblogs.com/houzichiguodong/p/9115394.html
https://www.runoob.com/python/python-json.html