python scrapy 獲取NBA東部賽區排名情況

目標數據:

 

items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class NbaItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    foot = scrapy.Field()
    win = scrapy.Field()
    defeat = scrapy.Field()
    percent = scrapy.Field()
    #落後場次
    lhcx = scrapy.Field()
    kechang = scrapy.Field()
    zhuchang = scrapy.Field()
    saiqu = scrapy.Field()
    lianmeng = scrapy.Field()
    lian = scrapy.Field()
    zuijin10 = scrapy.Field()
    

spider

# -*- coding: utf-8 -*-
import scrapy
from nba.items import NbaItem


class NnSpider(scrapy.Spider):
    name = 'nn'
    allowed_domains = ['data.sports.sohu.com']
    start_urls = ['http://data.sports.sohu.com/nba/nba_teams_rank.html?']

    def parse(self, response):
        item = NbaItem()
        dates = response.xpath(
            '//div[@class="east"]/div[@class="tab"]/table/tr')
        i = 0
        for date_s in dates:
            i = i+1
            if i == 1:
                pass
            else:
                item['name'] = "\t" + \
                    date_s.xpath('td[@class="e1"]/text()').extract()[0]
                item['foot'] = "\t" + \
                    date_s.xpath('td[@class="e2"]/a/text()').extract()[0]
                item['win'] = "\t" + \
                    date_s.xpath('td[@class="e3"][1]/text()').extract()[0]
                item['defeat'] = "\t" + \
                    date_s.xpath('td[@class="e3"][2]/text()').extract()[0]
                item['percent'] = "\t" + \
                    date_s.xpath('td[@class="e4"]/text()').extract()[0]
                item['lhcx'] = "\t" + \
                    date_s.xpath('td[@class="e5"][1]/text()').extract()[0]
                item['kechang'] = "\t" + \
                    date_s.xpath('td[@class="e5"][2]/text()').extract()[0]
                item['zhuchang'] = "\t" + \
                    date_s.xpath('td[@class="e5"][3]/text()').extract()[0]
                item['saiqu'] = "\t" + \
                    date_s.xpath('td[@class="e5"][4]/text()').extract()[0]
                item['lianmeng'] = "\t" + \
                    date_s.xpath('td[@class="e5"][5]/text()').extract()[0]
                item['zuijin10'] = "\t" + \
                    date_s.xpath('td[@class="e6"][2]/text()').extract()[0]
                item['lian'] = "\t"+date_s.xpath('td[@class="e6"][1]/text()').extract()[0].replace(
                    "\r", "").replace("\n", "").replace("\t", "").replace("\xa0", "").replace(" ", "")
                yield item

pipelines.py

# -*- coding: utf-8 -*-

# 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

import csv
import time

class NbaPipeline(object):

    def open_spider(self,spider):
        # 打開文件,指定方式爲寫,利用第3個參數把csv寫數據時產生的空行消除
        self.f = open('{}.csv'.format(time.strftime("%Y-%m-%d_%H_%M_%S")+'_NBA'),"w",newline="")
        # 設置文件第一行的字段名,注意要跟spider傳過來的字典key名稱相同
        self.fieldnames = ['name','foot','win','defeat','percent','lhcx','kechang','zhuchang','saiqu','lianmeng','zuijin10','lian']
        # 指定文件的寫入方式爲csv字典寫入,參數1爲指定具體文件,參數2爲指定字段名
        self.writer = csv.DictWriter(self.f, fieldnames=self.fieldnames)
        # 寫入第一行字段名,因爲只要寫入一次,所以文件放在__init__裏面
        self.writer.writeheader()

    def process_item(self, item, spider):
        self.writer.writerow(item)
        return item
    
    def close_spider(self,spider):
        self.f.close()
        

settings

# -*- coding: utf-8 -*-

# Scrapy settings for nba 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 = 'nba'

SPIDER_MODULES = ['nba.spiders']
NEWSPIDER_MODULE = 'nba.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# 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 = {
#    'nba.middlewares.NbaSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'nba.middlewares.NbaDownloaderMiddleware': 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 = {
   'nba.pipelines.NbaPipeline': 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'

源碼下載:https://download.csdn.net/download/Ferencz/12122448

 

 

 

 

發佈了13 篇原創文章 · 獲贊 3 · 訪問量 2427
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章