用python实现爬虫
一、安装
pip install Scrapy
安装后,只要在命令终端输入 scrapy,提示类似以下结果,代表已经安装成功。
二、新建项目(scrapy startproject)
在开始爬取之前,必须创建一个新的Scrapy项目。进入自定义的项目目录中,运行下列命令:
scrapy startproject mySpider
三、设置生成样式(mySpider/items.py)
我们打算抓取 http://www.itcast.cn/channel/teacher.shtml 网站里的所有讲师的姓名、职称和个人信息。
打开 mySpider 目录下的 items.py。
import scrapy
class ItcastItem(scrapy.Item):
name = scrapy.Field()
title = scrapy.Field()
info = scrapy.Field()
四、爬虫 (spiders/itcastSpider.py)
爬虫功能要分两步:
- 爬数据
在当前目录下输入命令,将在mySpider/spider目录下创建一个名为itcast的爬虫。
scrapy genspider itcast "itcast.cn"
打开 mySpider/spider目录里的 itcast.py:
import scrapy
class ItcastSpider(scrapy.Spider):
name = "itcast"
allowed_domains = ["itcast.cn"]
start_urls = ('http://www.itcast.cn/',)
def parse(self, response):
filename = "teacher.html"
open(filename, 'w', encodindg='utf-8').write(response.body.decode())
allow_domains = [] 域名范围。
start_urls = () :爬取网址。
parse(self, response) :解析的方法。
在mySpider目录下执行:
scrapy crawl itcast
生成teacher.html 文件,里面就是我们刚刚要爬取的网页的全部源代码信息。
- 取数据
xpath 方法,我们只需要输入的 xpath 规则就可以定位到相应 html 标签节点,详细内容可以查看 xpath 教程。不会 xpath 语法没关系,Chrome 给我们提供了一键获取 xpath 地址的方法(右键->检查->copy->copy xpath)
这里给出一些 XPath 表达式的例子及对应的含义:
/html/head/title: 选择HTML文档中 标签内的
# -*- coding: utf-8 -*-
import scrapy
class Opp2Spider(scrapy.Spider):
name = 'itcast'
allowed_domains = ['itcast.com']
start_urls = ['http://www.itcast.cn/']
def parse(self, response):
# 获取网站标题
context = response.xpath('/html/head/title/text()')
# 提取网站标题
title = context.extract_first()
print(title)
pass
执行以下命令:
scrapy crawl itcast
from mySpider.items import ItcastItem
def parse(self, response):
#open("teacher.html","wb").write(response.body).close()
# 存放老师信息的集合
items = []
for each in response.xpath("//div[@class='li_txt']"):
# 将我们得到的数据封装到一个 `ItcastItem` 对象
item = ItcastItem()
#extract()方法返回的都是unicode字符串
name = each.xpath("h3/text()").extract()
title = each.xpath("h4/text()").extract()
info = each.xpath("p/text()").extract()
#xpath返回的是包含一个元素的列表
item['name'] = name[0]
item['title'] = title[0]
item['info'] = info[0]
items.append(item)
return items
保存数据
scrapy保存信息的最简单的方法主要有四种,-o 输出指定格式的文件,命令如下:
scrapy crawl itcast -o teachers.json
json lines格式,默认为Unicode编码
scrapy crawl itcast -o teachers.jsonl
csv 逗号表达式,可用Excel打开
scrapy crawl itcast -o teachers.csv
xml格式
scrapy crawl itcast -o teachers.xml
参考链接:https://www.runoob.com/w3cnote/scrapy-detail.ht