精通python网络爬虫之自动爬取网页的爬虫 代码记录

时间:2023-03-08 22:36:57

items的编写

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

 # Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html import scrapy class AutopjtItem(scrapy.Item):
# define the fields for your item here like:
# 用来存储商品名
name = scrapy.Field()
#用来存储商品价格
price = scrapy.Field()
# 用来存储商品链接
link = scrapy.Field()
# 用来存储商品评论数
comnum = scrapy.Field()
# 用来存储商品评论内容链接
comnum_link = scrapy.Field()

piplines的编写

 # -*- coding: utf-8 -*-
import codecs
import json
# 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 class AutopjtPipeline(object):
def __init__(self):
self.file = codecs.open("D:/git/learn_scray/day11/1.json", "wb", encoding="utf-8") def process_item(self, item, spider):
# 爬取当前页的所有信息
for i in range(len(item["name"])):
name = item["name"][i]
price = item["price"][i]
link = item["link"][i]
comnum = item["comnum"][i]
comnum_link = item["comnum_link"][i]
current_conent = {"name":name,"price":price,"link":link,
"comnum":comnum,"comnum_link":comnum_link}
j = json.dumps(dict(current_conent),ensure_ascii=False)
# 为每条数据添加换行
line = j + '\n'
print(line)
self.file.write(line)
# for key,value in current_conent.items():
# print(key,value)
return item def close_spider(self,spider):
self.file.close()

自动爬虫编写实战

 # -*- coding: utf-8 -*-
import scrapy
from autopjt.items import AutopjtItem
from scrapy.http import Request class AutospdSpider(scrapy.Spider):
name = 'autospd'
allowed_domains = ['dangdang.com']
# 当当地方特产
start_urls = ['http://category.dangdang.com/pg1-cid10010056.html'] def parse(self, response):
item = AutopjtItem()
print("进入item")
# print("获取标题:")
# 获取标题
item["name"] = response.xpath("//p[@class='name']/a/@title").extract()
# print(title) # print("获取价格:")
# 价格
item["price"] = response.xpath("//span[@class='price_n']/text()").extract()
# print(price) # print("获取商品链接:")
# 获取商品链接
item["link"] = response.xpath("//p[@class='name']/a/@href").extract()
# print(link) # print("\n")
# print("获取商品评论数:")
# 获取商品评论数
item["comnum"] = response.xpath("//a[@name='itemlist-review']/text()").extract()
# comnum = response.xpath("//a[@name='itemlist-review']/text()").extract()
# print(comnum) # print("获取商品评论数链接:")
# 获取商品评论数链接
item["comnum_link"] = response.xpath("//a[@name='itemlist-review']/@href").extract()
# comnum_link = response.xpath("//a[@name='itemlist-review']/@href").extract()
# print(comnum_link)
yield item
for i in range(1,79):
# print(i)
url = "http://category.dangdang.com/pg"+ str(i) + "-cid10010056.html"
# print(url)
yield Request(url, callback=self.parse)

yield详解:

 https://*.com/questions/231767/what-does-the-yield-keyword-do

settings的设置:

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

 # Scrapy settings for autopjt project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'autopjt' SPIDER_MODULES = ['autopjt.spiders']
NEWSPIDER_MODULE = 'autopjt.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'autopjt (+http://www.yourdomain.com)' # Obey robots.txt rules
# 默认为true遵守robots.txt协议 我试了一下能爬 为了保险设置为false
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://doc.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://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'autopjt.middlewares.AutopjtSpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'autopjt.middlewares.AutopjtDownloaderMiddleware': 543,
#} # Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#} # Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'autopjt.pipelines.AutopjtPipeline': 300,
} # Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.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://doc.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'

最后的效果:

精通python网络爬虫之自动爬取网页的爬虫 代码记录