Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
crawls/
images/
__pycache__/
.vscode/
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
# python_scraping
Методы сбора и обработки данных из сети Интернет
# Методы сбора и обработки данных из сети Интернет
## Урок 7. Парсинг данных. ~~Selenium в Python~~ scrapy
1) Взять любую категорию товаров на сайте Леруа Мерлен. Собрать следующие данные:

* название;
* все фото;
* ссылка;
* цена.

Реализуйте очистку и преобразование данных с помощью ItemLoader. Цены должны быть в виде числового значения.

Дополнительно:

2) Написать универсальный обработчик характеристик товаров, который будет формировать данные вне зависимости от их типа и количества.
3) Реализовать хранение скачиваемых файлов в отдельных папках, каждая из которых должна соответствовать собираемому товару

PS: дополнительно реализована обработка ошибки 401 (защита QRATOR CSRF) в middleware и сохранение результатов в базе MongoDB
Empty file added products/__init__.py
Empty file.
39 changes: 39 additions & 0 deletions products/items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

from scrapy.item import Item, Field
from itemloaders.processors import MapCompose, TakeFirst, Compose, Identity
from scrapy.loader import ItemLoader
import re

def process_price(value):
try:
return int(re.sub(r'\D+', '', value))
except:
return value

def process_characteristics(value):
result = {}
backup = value.copy()
try:
while value: result |= {value.pop(0): value.pop(0)}
except:
result = backup

return result

class ProductsItem(Item):
url = Field()
name = Field()
price = Field()
images = Field()
characteristics = Field()

class ProductsLoader(ItemLoader):
default_output_processor = TakeFirst()
price_in = MapCompose(process_price)
images_out = Identity()
characteristics_in = Compose(process_characteristics)
characteristics_out = Identity()
154 changes: 154 additions & 0 deletions products/middlewares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals, Spider
from scrapy.http import Request, HtmlResponse
from scrapy.exceptions import IgnoreRequest

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class ProductsSpiderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.

@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s

def process_spider_input(self, response:HtmlResponse, spider):
# Called for each response that goes through the spider
# middleware and into the spider.

# Should return None or raise an exception.
return None

def process_spider_output(self, response:HtmlResponse, result, spider:Spider):
# Called with the results returned from the Spider, after
# it has processed the response.

# Must return an iterable of Request, or item objects.
for i in result:
yield i

def process_spider_exception(self, response:HtmlResponse, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.

# Should return either None or an iterable of Request or item objects.
pass

def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.

# Must return only requests (not items).
for r in start_requests:
yield r

def spider_opened(self, spider:Spider):
spider.logger.info('Павук открыт: %s' % spider.name)


class ProductsDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.

@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s

def process_request(self, request:Request, spider:Spider):
# Called for each request that goes through the downloader
# middleware.

# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
if hasattr(spider, 'state') and isinstance(spider.state, dict):
cookies = spider.state.get('cookies')
if isinstance(cookies, dict) and cookies and cookies.get('qrator_jsid') != request.cookies.get('qrator_jsid'):
request.cookies['qrator_jsid'] = cookies.get('qrator_jsid')
return None

def process_response(self, request:Request, response:HtmlResponse, spider:Spider):
# Called with the response returned from the downloader.

# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
if response.status == 401:
from urllib.parse import urlparse
p = urlparse(response.url)
if not p.netloc in ['leroymerlin.ru']:
return response

import requests, re
cookies = response.headers.getlist('Set-Cookie')
for coo in cookies:
if match := re.match('qrator_jsr=(.+?)-(.+?)-', coo.decode('utf-8')):
nonce, qsessid = match.groups()
spider.logger.info('Подбор знаничения pow')
session = requests.Session()
pow = 0
status = 403
while status == 403 and pow < 1280:
if not pow % 10:
print('.', end='', flush=True)

pow += 1
url = '%s://%s/__qrator/validate?pow=%s&nonce=%s&qsessid=%s' % (p.scheme, p.netloc, pow, nonce, qsessid)
r = session.post(url, json={})
if (status := r.status_code) == 200: break

else:
print()
spider.logger.error('Перебор pow завершился ничем. [%s]' % status)
return response

print()
cookies = r.cookies.get_dict()
if qrator_jsid := cookies.get('qrator_jsid'):
spider.logger.info('Значение найдено: pow=%s, qrator_jsid=%s' % (pow, qrator_jsid))
if not (hasattr(spider, 'state') and isinstance(spider.state, dict)):
spider.state = {}

if not isinstance(spider.state.get('cookies'), dict):
spider.state['cookies'] = {}

spider.state['cookies'].update(cookies)

return response.follow(response.url, cookies=request.cookies.update(cookies))
#break # for coo in cookies:

return response

def process_exception(self, request, exception, spider:Spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.

# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
#spider.logger.info('MIDDLEWARE: process_exception, %s' % request.cookies)
pass

def spider_opened(self, spider:Spider):
spider.logger.info('Павук открыт: %s' % spider.name)
68 changes: 68 additions & 0 deletions products/pipelines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# 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
import re, os.path
from itemadapter import ItemAdapter
from scrapy.pipelines.images import ImagesPipeline
from scrapy import Request
from scrapy.spiders import Spider
from scrapy.exceptions import DropItem
import pymongo


class ProductsPipeline:
collection_name = 'scrapy_products'

def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db

@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'products')
)

def open_spider(self, spider:Spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]

def close_spider(self, spider:Spider):
self.client.close()

def process_item(self, item, spider:Spider):
coll = self.db[self.collection_name]
doc = ItemAdapter(item).asdict()
#добавляем новые, обновялем старые (upsert=True)
if not coll.update_one({'url': doc['url']}, {'$set': doc}, upsert=True).upserted_id:
#raise DropItem('Duplicate item found')
pass

return item

class ProductsImagesPipeline(ImagesPipeline):
def get_media_requests(self, item, info):
if item.get('images'):
for img in item['images']:
try:
yield Request(img)
except Exception as e:
print(e)

def item_completed(self, results, item, info):
item['images'] = [itm[1] for itm in results if itm[0]]
return item

def file_path(self, request, response=None, info=None, *, item=None):
try:
parts = item['url'].split('/')
dir = parts[-1] if parts[-1] else parts[-2]
except Exception as e:
dir = ''

return os.path.join(dir, os.path.basename(request.url))
95 changes: 95 additions & 0 deletions products/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Scrapy settings for products 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 = 'products'

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

LOG_LEVEL = 'INFO'

#важно
IMAGES_STORE = 'images'

# 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/106.0.0.0 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 4

# 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 = 1.25
# 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
#COOKIES_DEBUG = True

# 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 = {
# 'products.middlewares.ProductsSpiderMiddleware': 543,

#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'products.middlewares.ProductsDownloaderMiddleware': 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 = {
'products.pipelines.ProductsPipeline': 200,
'products.pipelines.ProductsImagesPipeline': 100,
}

# 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'
4 changes: 4 additions & 0 deletions products/spiders/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
Loading