爬虫笔记18——selenium自动加载并存储vip(唯品会)网页数据

爬取唯品会的商品数据信息

整体的流程就是在唯品会首页搜索栏搜索对应的商品,然后跳转到对应商品页面进行数据的爬取、筛选和存储。

  • 其实也有另外一个爬取方案,不用selenium也是可以爬取到相应的数据,通过分析,搜索结果的页面是一个动态网页。动态页面的话这就要找到页面数据对应的接口,然后请求接口获取数据,我测试的时候返回的是个回调函数数据,把回调函数这个参数去掉它会变成json数据,然后进行筛选提取即可。有兴趣的可以去试试。

目前这里主要用的是selenium操作并返回网页的源代码提取数据:

思路分析:

1、 用selenium自动加载对应的网页数据,然后使用浏览器对象的page_source获取网页的源代码。

2、通过源代码,我们可以使用xpath的方式提取网页的商品数据信息。

3、最后就是把提取到的信息存储进去MongoDB数据库。

4、另外,要提取多页数据可以用格式化的方式改一下网页的参数,更改页面继续上面的操作即可。

代码示例:

python 复制代码
# -*- coding: utf-8 -*-
# @Time:      2024/06/29 11:59
# @File:       selenium爬取唯品会.py
#仅供学习参考

import pymongo
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 time


class SpiderVIP:
    def __init__(self, goods):
        # 商品关键词
        self.goods = goods
        # 数据库连接对象
        self.mongoDB = pymongo.MongoClient()
        self.connect = self.mongoDB['py_spider']['vip_data']
        # 创建浏览器驱动对象
        self.browser = webdriver.Chrome()
        # 创建等待操作对象
        self.wait_ob = WebDriverWait(self.browser, 10)
        self.url = 'https://category.vip.com'

    # 获取唯品会首页并搜索商品获取网页源代码
    def start(self):
        self.browser.get(self.url)

        # 如果网站采用了动态html技术,那么页面上的部分元素出现时间便不能确定,
        # 这个时候就可以设置一个等待时间,强制要求在时间内出现,否则报错。
        # presence_of_element_located:判定符合查询条件的一个元素是否存在
        search_input = self.wait_ob.until(EC.presence_of_element_located(
            (By.XPATH, "//input[@class='c-search-input  J-search-input']"))
        )
        search_input.send_keys(self.goods)

        search_button = self.wait_ob.until(EC.presence_of_element_located(
            (By.XPATH, "//a[@class='c-search-button  J-search-button  J_fake_a']")
        ))
        # 让检索框有充足的时间写入数据,程序休眠并加载完搜索按钮后点击
        time.sleep(2)
        search_button.click()
        time.sleep(2)

        self.roll_page()
        self.parse_page()

    def parse_page(self):
        div_list = self.browser.find_elements(
            By.XPATH,
            '//section[@id="J_searchCatList"]/div[@class="c-goods-item  J-goods-item c-goods-item--auto-width"]'
        )

        for div in div_list:
            price = div.find_element(
                By.XPATH,
                './/div[@class="c-goods-item__sale-price J-goods-item__sale-price"]'
            ).text

            title = div.find_element(
                By.XPATH,
                './/div[2]/div[2]'
            ).text

            item = {
                'title': title,
                'price': price
            }
            print(item)
            self.insert_mongo(item)
        self.click_next_page()

    # 页面滚动
    def roll_page(self):
        for i in range(1, 12):
            js_code = f"document.documentElement.scrollTop = {i * 1000}"
            self.browser.execute_script(js_code)
            time.sleep(1)

    def click_next_page(self):
        try:
            click_button = self.browser.find_element(By.XPATH, "//*[@id='J_page_special']/a[2]")
            if click_button:
                click_button.click()
                time.sleep(2)
                # 进入下一页解析页面
                self.roll_page()
                self.parse_page()
            else:
                self.browser.close()
        except Exception as e:
            print('没有下一页了', e)

    # 数据存储
    def insert_mongo(self, item):
        self.connect.insert_one(item)
        print('该条数据插入成功!')

    def main(self):
        self.start()


if __name__ == '__main__':
    search_value = input('输入要搜索的商品:')
    vip = SpiderVIP(search_value)
    vip.main()

MongoDB数据库信息如下:

相关推荐
IT数据小能手1 小时前
Python中爬虫编程的常见问题及解决方案
开发语言·爬虫·python
IT数据小能手5 小时前
天猫商品列表数据接口(Tmall.item_search)
大数据·爬虫·python
深圳市立年电子科技有限公司6 小时前
BMA580 运动传感器
人工智能·笔记·集成学习·射频工程
阿米诺s6 小时前
python本学期所有代码!
开发语言·爬虫·python
摸鱼仙人~8 小时前
python库 - json
经验分享·笔记·python·学习
supreme_1939 小时前
探索未来远程调试新纪元——《串口网口远程调试软件》:无缝连接,高效调试
经验分享·笔记·tcp/ip·信息与通信
IAMeee9 小时前
从项目中学习Bus-Off的快慢恢复
网络·笔记·学习·canoe·can总线·bus-off·干扰测试
半夏知半秋9 小时前
R语言学习笔记1-介绍与安装
开发语言·笔记·学习·r语言
张紫娃9 小时前
【鸿蒙学习笔记】数据类型
笔记·学习·harmonyos
IT数据小能手9 小时前
Python中的爬虫实战:百度知道爬虫
爬虫·python·百度