人生就应该多读一点鸡汤→传送门 : 格言网
好了废话不多说,直接上干活,今天是如何利用scrapy框架爬取格言网的全站数据并存储至本地.如何安装配置scrapy环境请看我的另一篇文章:Scrapy环境搭建
首先是创建一个scrapy框架的整体结构,这里就不做详细解释了.
这样一个整体的框架就构建出来了.
items.py:
(明确需要保存的字段,title 标题,url 标题对应的地址,content 鸡汤)
import scrapy
class GeyanItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
url = scrapy.Field()
content = scrapy.Field()
spiders→mingju.py:
(你的爬虫,如何爬取内容取决于这个)
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from geyan.items import GeyanItem
class MingjuSpider(CrawlSpider):
name = 'mingju'
allowed_domains = ['https://geyanw.com/']
start_urls = ['https://geyanw.com'] # 网址初始地址
def parse(self, response):
# i = {}
#i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
#i['name'] = response.xpath('//div[@id="name"]').extract()
#i['description'] = response.xpath('//div[@id="description"]').extract()
# return i
foo = response.xpath('//*[@id="p_left"]/div/dl/dd/ul/li') # xpath匹配需要爬取的内容
for i in foo:
item = GeyanItem() # 每一次都需要新实例化item 否则就会出现标题和url被最后获取的数据覆盖的情况
item['title'] = i.xpath('a/text()').extract_first() # extract()取出列表, extract_first()为单个数据
# url = 'https://geyanw.com/' + i.xpath('dd/ul/li[1]/a/@href').extract_first()
url = response.urljoin(i.xpath('a/@href').extract_first())
item['url'] = url
request = scrapy.Request(url=url, callback=self.content, dont_filter=True) # 同使用response.follow()方法
request.meta['item'] = item # 指定response给下一个方法, 对应需要取出的每一个数据
yield request
def content(self, response):
item = response.meta['item'] # 匹配对应的数据
bar = response.xpath('//*[@id="p_left"]/div[1]/div[4]/p')
mystr = ''
for i in bar:
mystr += i.xpath('text()').extract_first() # 拼接字符串内容
item['content'] = mystr
yield item
简单的爬取格言网内容的爬虫就大功告成了
最后还需要改一下setting配置,将user-agent改成浏览器内核,常见的防反爬手段
setting.py:
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' \
' Chrome/68.0.3423.2 Safari/537.36'
最后就是在控制台运行爬虫了:
最终效果(json格式的内容需要在菜鸟工具里转换后查看)→ json格式化菜鸟工具:
这样就使用scrapy框架完成了一个最简单的爬取网站的功能!