1. 程式人生 > 其它 >用response和scrapy爬取電影天堂電影的電影名並儲存下來

用response和scrapy爬取電影天堂電影的電影名並儲存下來

response

import requests
from lxml import etree

url='https://www.dytt89.com/html/bikan/'
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'}

response=requests.get(url,headers=headers)
response.encoding='gb2312'
tree=etree.HTML(response.text)
table_list
=tree.xpath('//div[@class="co_content8"]/ul/td/table') fp=open('movie.txt','w',encoding='utf-8')#把文字儲存到movietext上 for table in table_list: title=table.xpath('./tr[2]/td[2]/b/a[2]/text()')[0] print(title) # break #有break爬取一次,去掉爬取當前頁面所有 fp.write(title+'\n')#每行文字要換行 fp.close() print('
爬取完')

scrapy

(1)首先建立scrapy的檔案

 (2)movie中寫入資料並傳給items

import scrapy
from moviepro.items import MovieproItem

class MovieSpider(scrapy.Spider):
    name = 'movie'
    allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.dytt89.com/html/bikan/']

    def parse(self, response):
        table_llist=response.xpath('
//div[@class="co_content8"]/ul/td/table') for table in table_llist: title=table.xpath('./tr[2]/td[2]/b/a[2]/text()').extract_first() # print(title) item=MovieproItem() item['title']=title yield item

(3)在items中接受資料

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

import scrapy


class MovieproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # pass
    title =scrapy.Field()

(4)在settings裡面開啟管道配置USER_AGENT和引數

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

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


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

# Obey robots.txt rules
ROBOTSTXT_OBEY = False
LOG_LEVEL='ERROR'

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

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

(5)配置管道

# 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


class MovieproPipeline:
    fp=None#建立一個物件
    def open_spider(self,spider):
        self.fp=open('movie.txt','w',encoding='utf-8')
        print('開始爬取')
    def process_item(self, item, spider):
        title = item['title']#從item中取出東西
        self.fp.write(title+'\n')
        return item
    def close_spider(self,spider):
        self.fp.close()
        print('爬取成功')