详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

时间:2022-10-01 23:41:56

获取要爬取的url

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

爬虫前期工作

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

用pycharm打开项目开始写爬虫文件

字段文件items

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# define here the models for your scraped items
#
# see documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
 
import scrapy
 
 
class nbaprojectitem(scrapy.item):
  # define the fields for your item here like:
  # name = scrapy.field()
  # pass
  # 创建字段的固定格式-->scrapy.field()
  # 英文名
  engname = scrapy.field()
  # 中文名
  chname = scrapy.field()
  # 身高
  height = scrapy.field()
  # 体重
  weight = scrapy.field()
  # 国家英文名
  contryen = scrapy.field()
  # 国家中文名
  contrych = scrapy.field()
  # nba球龄
  experience = scrapy.field()
  # 球衣号码
  jerseyno = scrapy.field()
  # 入选年
  draftyear = scrapy.field()
  # 队伍英文名
  engteam = scrapy.field()
  # 队伍中文名
  chteam = scrapy.field()
  # 位置
  position = scrapy.field()
  # 东南部
  displayconference = scrapy.field()
  # 分区
  division = scrapy.field()

爬虫文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import scrapy
import json
from nbaproject.items import nbaprojectitem
 
class nbaspiderspider(scrapy.spider):
  name = 'nbaspider'
  allowed_domains = ['nba.com']
  # 第一次爬取的网址,可以写多个网址
  # start_urls = ['http://nba.com/']
  start_urls = ['https://china.nba.com/static/data/league/playerlist.json']
  # 处理网址的response
  def parse(self, response):
    # 因为访问的网站返回的是json格式,首先用第三方包处理json数据
    data = json.loads(response.text)['payload']['players']
    # 以下列表用来存放不同的字段
    # 英文名
    engname = []
    # 中文名
    chname = []
    # 身高
    height = []
    # 体重
    weight = []
    # 国家英文名
    contryen = []
    # 国家中文名
    contrych = []
    # nba球龄
    experience = []
    # 球衣号码
    jerseyno = []
    # 入选年
    draftyear = []
    # 队伍英文名
    engteam = []
    # 队伍中文名
    chteam = []
    # 位置
    position = []
    # 东南部
    displayconference = []
    # 分区
    division = []
    # 计数
    count = 1
    for i in data:
      # 英文名
      engname.append(str(i['playerprofile']['firstnameen'] + i['playerprofile']['lastnameen']))
      # 中文名
      chname.append(str(i['playerprofile']['firstname'] + i['playerprofile']['lastname']))
      # 国家英文名
      contryen.append(str(i['playerprofile']['countryen']))
      # 国家中文
      contrych.append(str(i['playerprofile']['country']))
      # 身高
      height.append(str(i['playerprofile']['height']))
      # 体重
      weight.append(str(i['playerprofile']['weight']))
      # nba球龄
      experience.append(str(i['playerprofile']['experience']))
      # 球衣号码
      jerseyno.append(str(i['playerprofile']['jerseyno']))
      # 入选年
      draftyear.append(str(i['playerprofile']['draftyear']))
      # 队伍英文名
      engteam.append(str(i['teamprofile']['code']))
      # 队伍中文名
      chteam.append(str(i['teamprofile']['displayabbr']))
      # 位置
      position.append(str(i['playerprofile']['position']))
      # 东南部
      displayconference.append(str(i['teamprofile']['displayconference']))
      # 分区
      division.append(str(i['teamprofile']['division']))
 
      # 创建item字段对象,用来存储信息 这里的item就是对应上面导的nbaprojectitem
      item = nbaprojectitem()
      item['engname'] = str(i['playerprofile']['firstnameen'] + i['playerprofile']['lastnameen'])
      item['chname'] = str(i['playerprofile']['firstname'] + i['playerprofile']['lastname'])
      item['contryen'] = str(i['playerprofile']['countryen'])
      item['contrych'] = str(i['playerprofile']['country'])
      item['height'] = str(i['playerprofile']['height'])
      item['weight'] = str(i['playerprofile']['weight'])
      item['experience'] = str(i['playerprofile']['experience'])
      item['jerseyno'] = str(i['playerprofile']['jerseyno'])
      item['draftyear'] = str(i['playerprofile']['draftyear'])
      item['engteam'] = str(i['teamprofile']['code'])
      item['chteam'] = str(i['teamprofile']['displayabbr'])
      item['position'] = str(i['playerprofile']['position'])
      item['displayconference'] = str(i['teamprofile']['displayconference'])
      item['division'] = str(i['teamprofile']['division'])
      # 打印爬取信息
      print("传输了",count,"条字段")
      count += 1
      # 将字段交回给引擎 -> 管道文件
      yield item

配置文件->开启管道文件

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# scrapy settings for nbaproject project
#
# for simplicity, this file contains only settings considered important or
# commonly used. you can find more settings consulting the documentation:
#
#   https://docs.scrapy.org/en/latest/topics/settings.html
#   https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#   https://docs.scrapy.org/en/latest/topics/spider-middleware.html
# ----------不做修改部分---------
bot_name = 'nbaproject'
 
spider_modules = ['nbaproject.spiders']
newspider_module = 'nbaproject.spiders'
# ----------不做修改部分---------
 
# crawl responsibly by identifying yourself (and your website) on the user-agent
#user_agent = 'nbaproject (+http://www.yourdomain.com)'
 
# obey robots.txt rules
# ----------修改部分(可以自行查这是啥东西)---------
# robotstxt_obey = true
# ----------修改部分---------
 
# configure maximum concurrent requests performed by scrapy (default: 16)
#concurrent_requests = 32
 
# configure a delay for requests for the same website (default: 0)
# see https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# see also autothrottle settings and docs
#download_delay = 3
# the download delay setting will honor only one of:
#concurrent_requests_per_domain = 16
#concurrent_requests_per_ip = 16
 
# disable cookies (enabled by default)
#cookies_enabled = false
 
# disable telnet console (enabled by default)
#telnetconsole_enabled = false
 
# override the default request headers:
#default_request_headers = {
#  'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#  'accept-language': 'en',
#}
 
# enable or disable spider middlewares
# see https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#spider_middlewares = {
#  'nbaproject.middlewares.nbaprojectspidermiddleware': 543,
#}
 
# enable or disable downloader middlewares
# see https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#downloader_middlewares = {
#  'nbaproject.middlewares.nbaprojectdownloadermiddleware': 543,
#}
 
# enable or disable extensions
# see https://docs.scrapy.org/en/latest/topics/extensions.html
#extensions = {
#  'scrapy.extensions.telnet.telnetconsole': none,
#}
 
# configure item pipelines
# see https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# 开启管道文件
# ----------修改部分---------
item_pipelines = {
  'nbaproject.pipelines.nbaprojectpipeline': 300,
}
# ----------修改部分---------
# enable and configure the autothrottle extension (disabled by default)
# see https://docs.scrapy.org/en/latest/topics/autothrottle.html
#autothrottle_enabled = true
# the initial download delay
#autothrottle_start_delay = 5
# the maximum download delay to be set in case of high latencies
#autothrottle_max_delay = 60
# the average number of requests scrapy should be sending in parallel to
# each remote server
#autothrottle_target_concurrency = 1.0
# enable showing throttling stats for every response received:
#autothrottle_debug = false
 
# enable and configure http caching (disabled by default)
# see https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#httpcache_enabled = true
#httpcache_expiration_secs = 0
#httpcache_dir = 'httpcache'
#httpcache_ignore_http_codes = []
#httpcache_storage = 'scrapy.extensions.httpcache.filesystemcachestorage'

管道文件 -> 将字段写进mysql

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# define your item pipelines here
#
# don't forget to add your pipeline to the item_pipelines setting
# see: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
 
 
# useful for handling different item types with a single interface
from itemadapter import itemadapter
 
import pymysql
class nbaprojectpipeline:
    # 初始化函数
  def __init__(self):
    # 连接数据库 注意修改数据库信息
    self.connect = pymysql.connect(host='域名', user='用户名', passwd='密码',
                    db='数据库', port=端口号)
    # 获取游标
    self.cursor = self.connect.cursor()
    # 创建一个表用于存放item字段的数据
    createtablesql = """
              create table if not exists `nbaplayer`(
              playerid int unsigned auto_increment,
              engname varchar(80),
              chname varchar(20),
              height varchar(20),
              weight varchar(20),
              contryen varchar(50),
              contrych varchar(20),
              experience int,
              jerseyno int,
              draftyear int,
              engteam varchar(50),
              chteam varchar(50),
              position varchar(50),
              displayconference varchar(50),
              division varchar(50),
              primary key(playerid)
              )charset=utf8;
              """
    # 执行sql语句
    self.cursor.execute(createtablesql)
    self.connect.commit()
    print("完成了创建表的工作")
    #每次yield回来的字段会在这里做处理
  def process_item(self, item, spider):
    # 打印item增加观赏性
    print(item)
    # sql语句
    insert_sql = """
    insert into nbaplayer(
    playerid, engname,
    chname,height,
    weight,contryen,
    contrych,experience,
    jerseyno,draftyear
    ,engteam,chteam,
    position,displayconference,
    division
    ) values (null,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
    """
    # 执行插入数据到数据库操作
    # 参数(sql语句,用item字段里的内容替换sql语句的占位符)
    self.cursor.execute(insert_sql, (item['engname'], item['chname'], item['height'], item['weight']
                     , item['contryen'], item['contrych'], item['experience'], item['jerseyno'],
                     item['draftyear'], item['engteam'], item['chteam'], item['position'],
                     item['displayconference'], item['division']))
    # 提交,不进行提交无法保存到数据库
    self.connect.commit()
    print("数据提交成功!")

启动爬虫

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

屏幕上滚动的数据

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

去数据库查看数据

详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库

简简单单就把球员数据爬回来啦~

到此这篇关于详解python之scrapy爬虫教程nba球员数据存放到mysql数据库的文章就介绍到这了,更多相关scrapy爬虫员数据存放到mysql内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_44864260/article/details/112986727