爬取淘宝商品-使用selenium

        爬取淘宝商品信息,基于selenium工具,基本思路:使用selenium打开浏览器进入淘宝页面并搜索管检测,等待页面加载完毕,在网页源代码中寻找信息。

        用于个人学习笔记,错误之处请指正。在代码中有详细注释。

1 准本工作

        寻找网址和搜索关键词,用于构造URL。

        需要使用selenium、pyquery和urllib库。

2 实现步骤

2.1 导包

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote

2.2 构造浏览器对象和关键词

# 构造请求
browser = webdriver.Edge()      # 狗在一个Edge对象
wait = WebDriverWait(browser, 10)       # 等待时间
KEYWORD = 'ipad'    # 关键词

2.3 获取商品列表

def index_page(page):
    """抓取索引页面 page:页码"""
    print(f"正在爬取{page}页")
    try:
        url = ('https://s.taobao.com/search?_input_charset=utf-8&commend=all&'
               'ie=utf8&initiative_id=tbindexz_20170306&page=1&q=') + quote(KEYWORD)
        browser.get(url)        # 请求网页
        if page > 1:
            # 等待跳转页码的输入框出现
            input = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, '#mainscrp-pager div.form > input')))
            # 等待跳转页面的“确定”按钮可点击
            submit = wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn,J_Submit')))
            input.clear()   # 清楚代码框内容
            input.send_keys(page)   # 输入指定的页码
            submit.click()  # 点击“确定”按钮
        # 等待页面跳转到指定页码
        wait.until(
            EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'),
                                              str(page)))
        # 等待商品出现
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item')))
        # get_products()     # 获取商品
    except TimeoutException:
        print("cuowu")

2.4 解析商品信息

def get_products():
    html = browser.page_source      # 获取网页源代码
    doc = pq(html)      # 构造pq对象
    items = doc('#mainsrp-itemlist .items .item').items()       # 从源代码中获取信息
    for item in items:
        product = {
            'image': item.find('.pic .img').attr('data-src'),       # 使用find方法寻找
            'price': item.find('.price').text(),
            'deal': item.find('.deal-cnt').text(),
            'title': item.find('.title').text(),
            'shop': item.find('.shop').text(),
        }
        print(product)
        # save_to_mongo(product)       # 保存数据

2.5 保存信息

def save_to_txt(product):
    with open('taobao_data.txt', 'a', encoding='utf-8') as file:
        file.write(product)

3 完整代码

# 使用selenium来模拟浏览器操作,抓取淘宝的商品信息
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote
from pyquery import PyQuery as pq

# 构造请求
browser = webdriver.Edge()      # 狗在一个Edge对象
wait = WebDriverWait(browser, 10)       # 等待时间
KEYWORD = 'ipad'    # 关键词

def index_page(page):
    """抓取索引页面 page:页码"""
    print(f"正在爬取{page}页")
    try:
        url = ('https://s.taobao.com/search?_input_charset=utf-8&commend=all&'
               'ie=utf8&initiative_id=tbindexz_20170306&page=1&q=') + quote(KEYWORD)
        browser.get(url)        # 请求网页
        if page > 1:
            # 等待跳转页码的输入框出现
            input = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, '#mainscrp-pager div.form > input')))
            # 等待跳转页面的“确定”按钮可点击
            submit = wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn,J_Submit')))
            input.clear()   # 清楚代码框内容
            input.send_keys(page)   # 输入指定的页码
            submit.click()  # 点击“确定”按钮
        # 等待页面跳转到指定页码
        wait.until(
            EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'),
                                              str(page)))
        # 等待商品出现
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item')))
        # get_products()     # 获取商品
    except TimeoutException:
        print("cuowu")

def get_products():
    html = browser.page_source      # 获取网页源代码
    doc = pq(html)      # 构造pq对象
    items = doc('#mainsrp-itemlist .items .item').items()       # 从源代码中获取信息
    for item in items:
        product = {
            'image': item.find('.pic .img').attr('data-src'),       # 使用find方法寻找
            'price': item.find('.price').text(),
            'deal': item.find('.deal-cnt').text(),
            'title': item.find('.title').text(),
            'shop': item.find('.shop').text(),
        }
        print(product)
        # save_to_mongo(product)       # 保存数据

def save_to_txt(product):
    with open('taobao_data.txt', 'a', encoding='utf-8') as file:
        file.write(product)

if __name__ == '__name__':
    index_page(1)    #抓取第一页的

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值