利用Python爬虫爬取美团热销榜前1000的店铺包括价格好评度等等以表格形式呈现。
要爬取美团热销榜前1000的店铺,我们可以使用Python的爬虫框架Scrapy来完成任务。以下是一个简单的示例代码:
-
创建一个Scrapy项目,使用命令
scrapy startproject meituan来创建项目。 -
进入项目目录,创建一个爬虫文件,使用命令
scrapy genspider meituan_spider meituan.com来创建爬虫文件。 -
在生成的爬虫文件中,我们需要定义如何抓取数据。以下是一个示例:
import scrapy
class MeituanSpider(scrapy.Spider):
name = 'meituan_spider'
allowed_domains = ['meituan.com']
start_urls = ['https://www.meituan.com/']
def parse(self, response):
# 提取店铺链接
shop_links = response.css('.index-nav-item.J-index-nav-item a::attr(href)').extract()
for shop_link in shop_links:
yield response.follow(shop_link, callback=self.parse_shop)
# 提取下一页链接
next_page = response.css('.icon.icon-arrow-right').xpath('../@href').extract_first()
if next_page:
yield response.follow(next_page, callback=self.parse)
def parse_shop(self, response):
# 提取店铺信息
name = response.css('.dealcard-brand a::text').extract_first()
price = response.css('.dealcard-price span:nth-child(1)::text').extract_first()
rating = response.css('.dealcard-rating strong::text').extract_first()
yield {
'name': name,
'price': price,
'rating': rating
}
- 在项目目录下的
settings.py文件中,添加以下配置:
ROBOTSTXT_OBEY = False
- 运行爬虫,使用命令
scrapy crawl meituan_spider -o meituan.csv来启动爬虫并将结果保存到meituan.csv文件中。
注意:上述代码只是一个简单示例,可能无法完全爬取所有店铺的信息。你可能需要根据实际情况对代码进行修改和优化。另外,爬取网站数据时要遵守网站的相关规定和法律法规
原文地址: https://www.cveoy.top/t/topic/hSr8 著作权归作者所有。请勿转载和采集!