使用selenium抓取1688供应商

本文介绍了一个使用Selenium和Python抓取1688网站商品数据的实战案例,通过自动化浏览器操作,实现了商品信息的批量抓取,并详细解析了网页结构,提取了包括商品链接、图片、价格等在内的多项关键数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了解决采购妹子一个个的翻,我将1688网上想找的产品撸了下来,这里以放一个词为代表。代码以及完整的数据结构已上传 https://github.com/jevy146/selenium_1688/

# -*- coding: utf-8 -*-
# @Time    : 2020/6/18 9:31
# @Author  : 结尾!!
# @FileName: D01-抓取首页信息.py
# @Software: PyCharm


from selenium.webdriver import ChromeOptions
import time
from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

#第一步实现对淘宝的登陆
class Chrome_drive():
    def __init__(self):
        ua = UserAgent()

        option = ChromeOptions()
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        option.add_experimental_option('useAutomationExtension', False)

        NoImage = {"profile.managed_default_content_settings.images": 2}  # 控制 没有图片
        option.add_experimental_option("prefs", NoImage)

        # option.add_argument(f'user-agent={ua.chrome}')  # 增加浏览器头部

        # chrome_options.add_argument(f"--proxy-server=http://{self.ip}")  # 增加IP地址。。

        # option.add_argument('--headless')  #无头模式 不弹出浏览器

        self.browser = webdriver.Chrome(options=option)
        self.browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
            'source': 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined})'
        })  #去掉selenium的驱动设置

        self.browser.set_window_size(1200,768)
        self.wait = WebDriverWait(self.browser, 12)

    def get_login(self):
        url='https://www.1688.com/'

        self.browser.get(url)
        #self.browser.maximize_window()  # 在这里登陆的中国大陆的邮编
        #这里进行人工登陆。
        time.sleep(2)
        self.browser.refresh()  # 刷新方法 refres
        return


    #获取判断网页文本的内容:
    def index_page(self,page,wd):
        """
        抓取索引页
        :param page: 页码
        """
        print('正在爬取第', page, '页')


        url = f'https://s.1688.com/selloffer/offer_search.htm?keywords=%D0%A1%D0%CD%C3%AB%BD%ED%BC%D3%C8%C8%B9%F1&n=y&netType=16&beginPage={page}#sm-filtbar'
        js1 = f" window.open('{url}')"  # 执行打开新的标签页
        print(url)
        self.browser.execute_script(js1)  # 打开新的网页标签
            # 执行打开新一个标签页。
        self.browser.switch_to.window(self.browser.window_handles[-1])  # 此行代码用来定位当前页面窗口
        self.buffer()  # 网页滑动  成功切换
            #等待元素加载出来
        time.sleep(3)
        self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#render-engine-page-container > div > div.common-pagination > div > div > div > span:nth-child(2) > input')))
            #获取网页的源代码
        html =  self.browser.page_source

        get_products(wd,html)

        self.close_window()


    def buffer(self): #滑动网页的
        for i in range(20):
            time.sleep(0.5)
            self.browser.execute_script('window.scrollBy(0,380)', '')  # 向下滑行300像素。

    def close_window(self):
        length=self.browser.window_handles
        print('length',length) #判断当前网页窗口的数量
        if  len(length) > 3:
            self.browser.switch_to.window(self.browser.window_handles[1])
            self.browser.close()
            time.sleep(1)
            self.browser.switch_to.window(self.browser.window_handles[-1])


import csv
def save_csv(lise_line):
    file = csv.writer(open("./1688_com.csv",'a',newline="",encoding="utf-8"))
    file.writerow(lise_line)

#解析网页,
from scrapy.selector import Selector
def get_products(wd,html_text):
    """
    提取商品数据
    """
    select=Selector(text=html_text)
    # 大概有47个
    items = select.xpath('//*[@id="sm-offer-list"]/div/*').extract()
    print('产品数 ',len(items))
    for i in range(1, len(items)+1):
        #详情页链接
        desc_href = select.xpath(f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="img-container"]//a/@href').extract_first()
        # 图片链接
        img_url  = select.xpath(f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="img"]/@style').extract_first()
        # 复购率
        shop_repurchase_rate = select.xpath(
            f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="desc-container"]//span[@class="shop-repurchase-rate"]/text()').extract_first()
        # title  # 标题
        title = select.xpath(
            f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="desc-container"]//div[@class="title"]//text()').extract()
        title_name=''.join(title)
        #price  #价格
        price = select.xpath(f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="desc-container"]//div[@class="price-container"]/div[@class="price"]/text()').extract_first()
        # sales_num  # 成交量
        sales_num = select.xpath(
            f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="desc-container"]//div[@class="price-container"]/div[@class="sale"]/text()').extract_first()
        #company_name  # 公司名称
        company_name = select.xpath(f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="company-name"]/a/text()').extract_first()
        #company_href  # 公司链接
        company_href = select.xpath(f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="company-name"]/a/@href').extract_first()
        #company_tag  # 公司标签
        company_tag = select.xpath(
            f'//*[@id="sm-offer-list"]/div[{i}]//div[@class="common-company-tag"]//text()').extract_first()

        all_desc=[wd,title_name,img_url,desc_href,price,sales_num,company_name,company_href,company_tag,shop_repurchase_rate]
        print(all_desc)
        save_csv(all_desc)




def main():
    """
    遍历每一页
    """
    run=Chrome_drive()
    run.get_login() #先扫码登录

    wd=['小型毛巾加热柜']
    for w in wd:

        for i in range(1, 6): #1688总计展示了6页,抓取了前5页的内容
            run.index_page(i,w)


if __name__ == '__main__':
    csv_head = 'word,title_name,img_url,desc_href,price,sales_num,company_name,company_href,company_tag,shop_repurchase_rate'.split(
        ',')
    save_csv(csv_head)
    main()

运行过程
在这里插入图片描述
3.运行结束 抓了5页,一页60个,没有遗漏的

在这里插入图片描述

爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43351935

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值