京东热卖手机信息爬取实战:Scrapy技巧与反爬策略/n/n本文将带您深入了解如何使用Scrapy框架爬取京东热卖手机信息,并提供相应的代码示例。我们将涉及以下内容:/n/n* 获取指定品牌手机信息(名称、价格、评价数量、是否自营)/n* 对获取的信息去重,去除相同品牌相同型号的手机/n* 获取手机的详细参数信息/n* 将手机的详细参数信息保存为Excel文件/n/n注意:由于涉及到京东网站的爬取,我们需要留意京东网站的反爬机制,并采取相应的策略,例如设置User-Agent、使用代理IP等。/n/n### 代码示例/n/npython/nimport scrapy/nimport re/nimport json/nimport xlwt/n/nclass JDPhoneSpider(scrapy.Spider):/n name = 'jdphone'/n allowed_domains = ['jd.com']/n start_urls = [/n 'https://search.jd.com/Search?keyword=华为手机&enc=utf-8&wq=华为手机',/n 'https://search.jd.com/Search?keyword=小米手机&enc=utf-8&wq=小米手机',/n 'https://search.jd.com/Search?keyword=苹果手机&enc=utf-8&wq=苹果手机'/n ]/n custom_settings = {/n 'DOWNLOAD_DELAY': 1,/n 'CONCURRENT_REQUESTS_PER_DOMAIN': 1,/n 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'/n }/n/n def parse(self, response):/n # 获取搜索结果页中的所有手机链接/n phone_links = response.css('div#J_goodsList li.gl-item div.p-name a::attr(href)').extract()/n for link in phone_links:/n yield scrapy.Request(link, callback=self.parse_phone)/n/n # 获取下一页链接/n next_page = response.css('a.fp-next::attr(href)').extract_first()/n if next_page:/n yield scrapy.Request('https://search.jd.com' + next_page, callback=self.parse)/n/n def parse_phone(self, response):/n # 获取手机名称、价格、评价数量、是否自营/n name = response.css('div.sku-name::text').extract_first().strip()/n price = response.css('div.summary-price-wrap span.p-price strong::text').extract_first()/n comment_count = response.css('div.comment-count a::text').extract_first()/n is_self_operated = '是' if response.css('div.self-operated').extract_first() else '否'/n/n # 获取手机参数信息/n params = {}/n param_items = response.css('ul.parameter2 li')/n for item in param_items:/n key = item.css('span.p-name::text').extract_first().strip()/n value = item.css('span.p-value::text').extract_first().strip()/n params[key] = value/n/n # 将数据保存为item/n item = {/n 'name': name,/n 'price': price,/n 'comment_count': comment_count,/n 'is_self_operated': is_self_operated,/n 'params': params/n }/n yield item/n/n def closed(self, reason):/n # 将数据保存为excel文件/n book = xlwt.Workbook(encoding='utf-8')/n sheet = book.add_sheet('phones')/n row = 0/n sheet.write(row, 0, '品牌')/n sheet.write(row, 1, '型号')/n sheet.write(row, 2, '价格')/n sheet.write(row, 3, '评价数量')/n sheet.write(row, 4, '是否自营')/n sheet.write(row, 5, '颜色')/n sheet.write(row, 6, '屏幕尺寸')/n sheet.write(row, 7, 'CPU型号')/n sheet.write(row, 8, 'RAM')/n sheet.write(row, 9, 'ROM')/n for brand in ['华为', '小米', '苹果']:/n phones = self.get_phones_by_brand(brand)/n models = set([phone['name'] for phone in phones])/n for model in models:/n phones_of_model = [phone for phone in phones if phone['name'] == model]/n phone = phones_of_model[0]/n row += 1/n sheet.write(row, 0, brand)/n sheet.write(row, 1, phone['name'])/n sheet.write(row, 2, phone['price'])/n sheet.write(row, 3, phone['comment_count'])/n sheet.write(row, 4, phone['is_self_operated'])/n for key, value in phone['params'].items():/n if key == '颜色':/n sheet.write(row, 5, value)/n elif key == '屏幕尺寸':/n sheet.write(row, 6, value)/n elif key == 'CPU型号':/n sheet.write(row, 7, value)/n elif key == 'RAM':/n sheet.write(row, 8, value)/n elif key == 'ROM':/n sheet.write(row, 9, value)/n book.save('phones.xls')/n/n def get_phones_by_brand(self, brand):/n phones = []/n for item in self.crawler.stats.get_stats():/n if item[0].startswith('jdphone'):/n data = json.loads(item[1])/n if data['name'] == brand:/n phones.extend(data['phones'])/n return phones/n/n def process_item(self, item, spider):/n # 对数据进行去重处理/n brand = re.search(r'(/w+)手机', spider.start_urls[0]).group(1)/n model = item['name']/n for item in self.crawler.stats.get_stats():/n if item[0].startswith('jdphone'):/n data = json.loads(item[1])/n if data['name'] == brand:/n phones = data['phones']/n if any([phone['name'] == model for phone in phones]):/n return item/n else:/n phones.append(item)/n self.crawler.stats.set_value('jdphone', json.dumps({'name': brand, 'phones': phones}))/n return item/n self.crawler.stats.set_value('jdphone', json.dumps({'name': brand, 'phones': [item]})) /n return item/n/n/n### 代码解读/n/n1. 基础配置/n * name:爬虫名称/n * allowed_domains:允许爬取的域名/n * start_urls:爬取的起始链接/n * custom_settings:自定义爬虫设置,包括下载延迟、并发请求限制、User-Agent等/n/n2. 解析搜索结果页/n * 使用response.css()选择器获取所有手机链接/n * 使用scrapy.Request()发起新的请求,解析每个手机页面/n * 使用response.css('a.fp-next::attr(href)').extract_first()获取下一页链接,继续爬取/n/n3. 解析手机页面/n * 使用response.css()选择器获取手机名称、价格、评价数量、是否自营/n * 使用response.css('ul.parameter2 li')获取手机参数信息/n * 将数据封装为字典并yield/n/n4. 数据去重/n * 使用process_item方法对数据进行去重处理,保证每个品牌的每个型号只会被保存一次/n * 使用get_phones_by_brand方法获取同一个品牌的手机信息/n * 使用set去重,并确保每个型号只保存一次/n/n5. 保存数据/n * 使用closed方法在爬虫关闭时将数据保存为Excel文件/n * 将数据写入Excel文件,包括品牌、型号、价格、评价数量、是否自营、颜色、屏幕尺寸、CPU型号、RAM、ROM等/n/n### 反爬策略/n/n 设置User-Agent: 通过自定义custom_settings中的USER_AGENT设置伪造浏览器信息,避免被识别为爬虫/n 下载延迟: 通过custom_settings中的DOWNLOAD_DELAY设置下载延迟,降低爬取频率,避免对目标网站造成过大压力/n* 代理IP: 可以使用代理IP来隐藏真实IP地址,绕过网站的IP封锁/n/n注意:** 即使采取了反爬策略,也需要谨慎爬取网站数据,避免过度爬取导致网站崩溃或被封禁。/n/n希望本文能够帮助您快速上手使用Scrapy爬取京东热卖手机信息。如果您在爬取过程中遇到问题,请随时提问。

京东热卖手机信息爬取实战:Scrapy技巧与反爬策略

原文地址: https://www.cveoy.top/t/topic/ol7e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录