项目开始

第一步仍然是创建scrapy项目与Spider文件

切换到工作目录两条命令依次输入

scrapy startproject xunleidianying scrapy genspider xunleiBT xl720/thunder/years/2019

内容分析

打开目标网站(分类是2019年上映的电影),分析我们需要的数据

python爬虫爬pdf(scrapy爬取迅雷电影天堂最新电影ed2k)(1)

进入页面是列表的形式就像豆瓣电影一样,然后我们点进去具体页面看看

python爬虫爬pdf(scrapy爬取迅雷电影天堂最新电影ed2k)(2)

这个页面就是我们需要拿到的内容页面,我们来看我们需要哪些数据(某些数据从第一个页面就可以获得,但是下载地址必须到第二个页面)

分析完成之后就可以首先编写 items.py文件

import scrapy ''' 更多Python学习资料以及源码教程资料,可以在群821460695 免费获取 ''' class XunleidianyingItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name = scrapy.Field() information = scrapy.Field() content = scrapy.Field() downloadurl = scrapy.Field() pass

另外别忘了去settings.py中开启 ITEM_PIPELINES 选项

爬虫文件编写

老样子,为了方便测试我们的爬虫,首先编写一个main.py的文件方便IDE调用

main.py:

import scrapy.cmdline scrapy.cmdline.execute('scrapy crawl xunleiBT'.split())

首先我们先测试直接向目标发送请求是否可以得到响应

爬虫文件 xunleiBT.py编写如下:

# -*- coding: utf-8 -*- import scrapy class XunleibtSpider(scrapy.Spider): name = 'xunleiBT' allowed_domains = ['xl720/thunder/years/2019'] start_urls = ['xl720/thunder/years/2019/'] def parse(self, response): print(response.text) pass

运行 main.py 看看会出现什么

python爬虫爬pdf(scrapy爬取迅雷电影天堂最新电影ed2k)(3)

好的,发现直接返回正常的网页也就是我们要的网页,说明该网站没有反爬机制,这样我们就更容易爬取了

然后通过xpath定位页面元素,具体就不再赘述,之前的scarpy教程中都有 继续编写爬虫文件

import scrapy #导入编写的 item from xunleidianying.items import XunleidianyingItem ''' 更多Python学习资料以及源码教程资料,可以在群821460695 免费获取 ''' class XunleibtSpider(scrapy.Spider): name = 'xunleiBT' allowed_domains = ['xl720'] start_urls = ['xl720/thunder/years/2019/'] def parse(self, response): url_list = response.xpath('//h3//@href').getall() for url in url_list: yield scrapy.Request(url,callback=self.detail_page) nextpage_link = response.xpath('//a[@class="nextpostslink"]/@href').get() if nextpage_link: yield scrapy.Request(nextpage_link, callback=self.parse) def detail_page(self,response): # 切记item带括号 BT_item = XunleidianyingItem() BT_item['name'] = response.xpath('//h1/text()').get() BT_item['information'] = ''.join(response.xpath('//div[@id="info"]//text()').getall()) BT_item['content'] = response.xpath('//div[@id="link-report"]/text()').get() BT_item['downloadurl'] = response.xpath('//div[@class="download-link"]/a/text() | //div[@class="download-link"]/a/@href').getall() yield BT_item

ITEM爬取完成后该干什么?当然是入库保存了,编写pipelines.py文件进行入库保存

再次提醒别忘了去settings.py中开启 ITEM_PIPELINES 选项

pipelines.py文件代码如下:

import pymongo #连接本地数据库 myclient = pymongo.MongoClient("mongodb://localhost:27017/") #数据库名称 mydb = myclient["movie_BT"] #数据表名称 mysheet = mydb["movie"] ''' 更多Python学习资料以及源码教程资料,可以在群821460695 免费获取 ''' class XunleidianyingPipeline(object): def process_item(self, item, spider): data = dict(item) mysheet.insert(data) return item

再次运行main.py 等待运行完成后打开数据库查询

python爬虫爬pdf(scrapy爬取迅雷电影天堂最新电影ed2k)(4)

数据保存完成,这次我们一共导入了380个数据,可以愉快的查看电影了

,