1.前言

1.1 课题描述

爬取苏宁易购商品(apple)信息(https://www.suning.com/):商品图片链接(image),商品价格(price),商品标题(title),商品被评论数(comment_num),商品所属店家(shop),并将其保存在MongoDB(连接:localhost,数据库:suning,集合:products)中。

1.2 课题背景及意义

如今,人类社会已经进入了大数据时代,数据已经成为必不可少的部分,可见数据的获取非常重要。而爬虫作为获取数据的一大利器,可以让我们获取足够的数据并用于实际分析。

练习爬虫能力,获取苏宁易购商品信息的详细信息,并用于之后的处理与分析。

1.3 相关技术介绍

selenium:一个Python第三方库。Selenium是最广泛使用的开源Web UI(用户界面)自动化测试套件之一。它最初由杰森·哈金斯(Jason Huggins)于2004年开发,作为Thought Works的内部工具。Selenium支持跨不同浏览器,平台和编程语言的自动化。

本次项目主要使用selenium来模拟人工访问。

pyquery:Python第三方库,pyquery相当于jQuerypython实现,可以用于解析HTML网页等。

本次项目主要使用pyquery.PyQuery来解析HTML网页。

webdriver_manager.chrome:一个Python第三方库,使用它可以避免安装driver插件,使用便捷。

本次项目主要使用webdriver_manager.chrome.ChromeDriverManager来模拟运行chrome浏览器。

pymongo:一个Python第三方库,用于python操纵MongoDB。

time:Python库,可以用于格式化日期和时间。

re:Python库,用于正则匹配。

2.系统分析

爬取苏宁易购商品(apple)信息(https://www.suning.com/):商品图片链接(image),商品价格(price),商品标题(title),商品被评论数(comment_num),商品所属店家(shop),并将其保存在MongoDB(连接:localhost,数据库:suning,集合:products)中。

输出结果的图片(部分)

image-20211110194125486

保存的MongoDB的图片(部分)

image-20211110194155096

3.系统设计

爬取苏宁易购商品信息

4.系统实现

4.1 运行界面

image-20211110195357577

4.2 代码实现

#!/usr/bin/env python
# coding: utf-8

# In[1]:


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
import time
import pymongo
from selenium.webdriver.common.keys import Keys
from pyquery import PyQuery as pq
from webdriver_manager.chrome import ChromeDriverManager


# In[2]:

# 爬取商品信息
class Search:
    def __init__(self, url, keyword, driver, db):
        self.url = url
        self.keyword = keyword
        self.driver = driver
        self.db = db

    # 进入苏宁易购首页  
    def get_front_page(self):
        self.driver.get(self.url)

    # 进入商品页面
    def get_commodity_page(self):
        # 输入的搜索框
        input = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#searchKeywords'))
        )
        # 搜索按钮
        submit = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "#searchSubmit")))
        input.send_keys(self.keyword)
        submit.click()

    # 获得总页面数量
    def get_page_num(self):
        target = self.driver.find_element_by_css_selector('#bottom_pager > div > span.page-more')
        self.driver.execute_script("arguments[0].scrollIntoView();", target)
        time.sleep(3)
        total = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#bottom_pager > div > span.page-more')))
        total_text = total.text
        # 正则处理
        pattern = re.compile('\S\S(\d+).*?')
        result = re.search(pattern, total_text)
        self.total = int(result.group(0)[1:])

    # 获取商品信息并且存储
    def get_content(self):
        try:
            # 选择展示框
            WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, '#product-list .item-wrap')))

            html = self.driver.page_source
            doc = pq(html)
            # 获得所有商品的数据
            items = doc('#product-list .item-wrap').items()
            for item in items:
                proucts = {
                    'image': item.find(".img-block")('a')('img').attr('src').strip().replace('//', ' '),
                    'price': item.find('.def-price').text().replace('\n', ' '),
                    'title': item.find('.title-selling-point').text().strip().replace('\n', ' '),
                    'comment_num': item.find('.info-evaluate')('a')('i').text(),
                    'shop': item.find('.store-stock').text(),
                }
                print(proucts)
                # 保存在products集合中
                try:
                    self.db['products'].insert_one(proucts)
                except:
                    continue
        except:
            return

    # 进行商品页面的翻页
    def to_next_page(self):
        for page in range(1, self.total + 1):
            print('当前页:%d/%d' % (page, self.total))
            try:
                # 找到输入框
                time.sleep(1)
                inputs = WebDriverWait(self.driver, 20).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, '#bottomPage')))
                time.sleep(1)
                inputs.clear()
                # 找到确定按钮
                submit = WebDriverWait(self.driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.CSS_SELECTOR, "#bottom_pager > div > a.page-more.ensure")))
                inputs.send_keys(page)
                submit.send_keys(Keys.ENTER)
                target = self.driver.find_element_by_css_selector('#bottom_pager > div > span.page-more')
                # 将页面下拉至底部
                self.driver.execute_script("arguments[0].scrollIntoView();", target)
                time.sleep(3)
                self.get_content()
                # 进行判定
                WebDriverWait(self.driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.CSS_SELECTOR, '#bottom_pager > div > a.cur')), str(page))
            except:
                print("wrong page!")
                return
        self.driver.close()


# In[3]:


if __name__ == '__main__':
    url = 'https://www.suning.com/'
    keyword = 'apple'
    driver = webdriver.Chrome(ChromeDriverManager().install())
    # 连接MongoDB
    client = pymongo.MongoClient('localhost')
    db = client['suning']
    try:
        db.drop_collection('products')
        db.create_collection('products')
    except:
        db.create_collection('products')
    # 开始爬取
    search = Search(url, keyword, driver, db)
    search.get_front_page()
    search.get_commodity_page()
    search.get_page_num()
    search.to_next_page()

5.结束语

对爬虫有了新的了解,学会了使用selenium来爬取信息。

最后修改:2021 年 12 月 14 日 08 : 23 PM