今天我们利用scrapy框架爬取数据,然后将数据储存到MySQL中,话不多说,今天我们爬取的网页是:http://www.ygdy8.com,我们要获取经典电影分类中的国内电影,日韩电影,欧美电影三个分类的第一页的详情页,并从详情页中获取到电影的名称以及下载的链接。
1.创建Scrapy框架和爬虫程序。
2.定义settings.py
3.在movie.py编写爬虫程序
# -*- coding: utf-8 -*-
import scrapy
from ..items import YanguangItem
class MovieSpider(scrapy.Spider):
name = 'movie'
allowed_domains = ['ygdy8.com']
# 更改初始的url,此网址为经典影片的网址
start_urls = ['http://www.ygdy8.com/html/gndy/index.html']
# 获取‘更多’选项的链接,(只获取国内,日韩,欧美三个分类)
def parse(self, response):
info_list=response.xpath('//div[@class="title_all"]/p/em/a/@href').extract()[:3]
for info in info_list:
# 拼接完整的‘更多’网址
info='http://www.ygdy8.com'+info
yield scrapy.Request(url=info,callback=self.get_movie_url)
# 获取每部电影进入详情页的网址
def get_movie_url(self,response):
movie_url=response.xpath('//a[@class="ulink"][2]/@href').extract()
for movie in movie_url:
# 拼接完整的url
movie='http://www.ygdy8.com'+movie
yield scrapy.Request(url=movie,callback=self.get_content_in_url)
# 获取每部电影的名字,以及他们的下载链接
def get_content_in_url(self,response):
mov_name=response.xpath('//div[@class="title_all"]/h1/font/text()').extract_first('')
print(mov_name)
mov_href=response.xpath('//td[@style="WORD-WRAP: break-word"]/a/@href').extract_first('')
print(mov_href)
print('------------------------------------------------------------')
item=YanguangItem()
item['mov_name']=mov_name
item['mov_href']=mov_href
yield item
4.items.py
import scrapy
class YanguangItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
mov_name=scrapy.Field()
mov_href=scrapy.Field()
pass
5.建立MySQL数据库和表格
打开MySQLWorkbench.exe,进入主界面创建数据和表格
这里我们创建一个名字为Movie的数据库,里面创建一个名字为movieTable的表格,有两个标题,name和href,注意更改为utf-8格式。
6.在Pipelines.py中自定义连接数据库,写入数据
# -*- 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 pymysql
class YanguangPipeline(object):
def __init__(self):
# 连接MySQL数据库
self.connect=pymysql.connect(host='localhost',user='root',password='123456',db='Movie',port=3306)
self.cursor=self.connect.cursor()
def process_item(self, item, spider):
# 往数据库里面写入数据
self.cursor.execute('insert into movieTable(name,href)VALUES ("{}","{}")'.format(item['mov_name'],item['mov_href']))
self.connect.commit()
return item
# 关闭数据库
def close_spider(self,spider):
self.cursor.close()
self.connect.close()
7.完成后,在终端输入命令scrapy crawl movie
点击红色的圈刷新一下,出现如图所示的数据,便算是存储数据成功。
将数据存储到MySQL数据库中实际和sqlite3数据库的操作相差不大,只要用心练习,很快便能熟练掌握。