Я пытаюсь очистить сайт Google Покупок от всех деталей продукта. Хотя, макет различается для разных поисковых запросов. Как я могу учесть разные макеты в коде Scrapy? например: для ключевого слова батут отображается сетка, а для обоев продукты отображаются горизонтальными плитками
KEYWORDS = ['wallpaper'
'trampoline',
'seesaws']
class SerpItem(Item):
date = Field()
keyword = Field()
devicetype = Field()
position = Field()
url = Field()
title = Field()
price=Field()
company=Field()
class BaseSpider(Spider):
name = 'base'
allowed_domains = ['google.com']
def start_requests(self):
for keyword in KEYWORDS:
url = 'https://www.google.com/search?tbm=shop&q='+keyword.replace(' ','+')
yield Request(url=url, meta=dict(keyword=keyword))
def parse(self, response):
results = response.xpath(self.xpath['results'])
for i, result in enumerate(results):
item = SerpItem()
item['date'] = datetime.now().strftime('%Y-%m-%d')
item['keyword'] = response.meta['keyword']
item['devicetype'] = self.devicetype
item['position'] = i + 1
for label in ['url', 'title']:
if self.xpath[label]:
item[label] = result.xpath(self.xpath[label]).extract_first() or ''
if item['url'] :
url_update = ['https://www.google.com'+item['url']]
item['url'] = url_update
item['price'] = ' '.join(result.xpath(self.xpath['price']).extract())
item['company'] = ' '.join(result.xpath(self.xpath['company']).extract())
yield item
class DesktopSpider(BaseSpider):
name = 'desktop'
custom_settings = {
'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
}
xpath = {
'results': '//div[@class="sh-dgr__gr-auto sh-dgr__grid-result"]',
'url': './/div[@class="sh-dgr__offer-content"]/a/@href',
'title': './/div[@class="sh-dgr__content"]/a/h4/text()' ,
'price': './/div[@class="sh-dgr__offer-content"]/span/span[@aria-hidden="true"]/text()',
'company': './/div[@class="sh-dgr__offer-content"]/a/text()'
}
devicetype = 'desktop'
process = CrawlerProcess(settings={
"FEEDS": {
"items.csv": {"format": "csv"},
},
"DOWNLOAD_DELAY": 15,
"ROBOTSTXT_OBEY": False
})
process.crawl(DesktopSpider)
process.start()