前言
编写scrapy框架软件:pycharm
mysql图形界面工具:navicat
mongodb图形界面工具:Robo 3T
浏览器:Google谷歌
爬取网站:https://china.nba.com/
安装pymysql:在命令行:pip install pymysql
安装pymongo:在命令行:pip install pymongo
一、分析网站
我们将爬取NBA网站的首页的要闻(如图背景为蓝色)
查看源代码并分析
在谷歌浏览器可以选中我们爬取的内容右键copy–copy xpath (不过我喜欢用css选择器)
二、编写爬虫
1、编写item
class MysqlItem(scrapy.Item):
# define the fields for your item here like:
news = scrapy.Field()
url = scrapy.Field()
pass
2、编写spider
import scrapy
from mysql.items import MysqlItem
class SqlSpider(scrapy.Spider):
name = 'sql'
allowed_domains = ['nba.com']
start_urls = ['https://china.nba.com/']
def parse(self, response):
list = response.css('.impnews-wrap ul:first-child li')#ul:first-child代表第一个ul标签
for sel in list:
item = MysqlItem()
item['title'] = sel.css('a span::text').extract()[0]
item['url'] = sel.css('a::attr(href)').extract()[0]
yield item
3、在settings.py开启item pipelines
ITEM_PIPELINES = {
'mysql.pipelines.MysqlPipeline': 300,
'mysql.pipelines.MongodbPipeline': 400,
}
4、编写保存到MySQL的pipelines
import pymysql
import pymysql.cursors
class MysqlPipeline(object):
def __init__(self):
self.conn = pymysql.connect(host="localhost",port=3306,user = 'root',password="123456",db="nba",charset='utf8')
self.cur = self.conn.cursor()#游标对象
print('成功连接到数据库')
def close_spider(self, spider):
print('关闭数据库')
self.cur.close()
self.conn.close()
def process_item(self, item, spider):
sql = "INSERT INTO news VALUES('"+item["news"]+"','"+item["url"]+"')"
self.cur.execute(sql)
self.conn.commit()
return item
5、编写保存到mongodb的pipelines
import pymongo
class MongodbPipeline(object):
def __init__(self):
host = 'localhost'
port = 27017
db_name ='nba' #数据库名称
client = pymongo.MongoClient(host=host, port=port)
db = client[db_name]
self.post = db['news'] # collections的名字
def process_item(self, item, spider):
data = dict(item)
self.post.insert(data)
return item
三、运行项目
scrapy crawl sql (sql是我的爬虫文件)
在navicat软件我们看到爬取的数据保存到mysql数据库了
在Tobo 3T软件我们看到爬取的数据保存到mongodb数据库了
四、注意点
保存在MySQL数据库需要提前建立数据库和表。
保存在mongodb则不需要。