0.创建一个项目
1.items 定义数据结构的
2.使用xpath解析到爬取数据
3.使用管道
items.py文件:
import scrapy
class MyspiderItem(scrapy.Item):
# define the fields for your item here like:
name = scrapy.Field() # 表示讲师姓名
level = scrapy.Field() # 表示讲师级别
resume = scrapy.Field() # 表示讲师履历
pass
spiders/dsangdang.py文件
import scrapy
from mySpider.items import MyspiderItem
class ItcastSpider(scrapy.Spider):
name = "itcast"
allowed_domains = ["
http://www.itcast.cn"]
start_urls = ["
https://www.itcast.cn/channel/teacher.shtml"]
def parse(self, response):
# with open("teacher_info.txt", "w", encoding="utf-8") as file:
# file.write(response.text)
# pass
items = [] # 存储所有讲师的信息
for each in response.xpath("//div[@class='li_txt']"):
item = MyspiderItem( ) # 创建MyspiderItem类的对象
name = each.xpath("h3/text()").extract_first()
level = each.xpath("h4/text()").extract()
resume = each.xpath("p/text()").extract()
item["name"] = name
item["level"] = level[0]
item["resume"] = resume[0]
yield item
# items.append(item)
# return items
pipeline.py文件
# 如果想使用管道的话 那么就必须在settings中开启管道
class ScrapyDangdang095Pipeline:
# 在爬虫文件开始的之前就执行的一个方法
def open_spider(self,spider):
self.fp = open('book.json','w',encoding='utf-8')
# item就是yield后面的book对象
def process_item(self, item, spider):
# 以下这种模式不推荐 因为每传递过来一个对象 那么就打开一次文件 对文件的操作过于频繁
# # (1) write方法必须要写一个字符串 而不能是其他的对象
# # (2) w模式 会每一个对象都打开一次文件 覆盖之前的内容
# with open('book.json','a',encoding='utf-8')as fp:
# fp.write(str(item))
self.fp.write(str(item))
return item
# 在爬虫文件执行完之后 执行的方法
def close_spider(self,spider):
self.fp.close()