文章附件下载:https://www.pan38.com/dow/share.php?code=JCnzE 提取密码:2778
代码功能说明:
使用Selenium实现自动化操作淘宝卖家后台
支持三种核心功能:批量上传商品、批量上架商品和批量发货
商品信息通过Excel文件导入,支持多商品批量处理
包含完善的异常处理和等待机制,确保操作稳定性
采用面向对象设计,代码结构清晰易于扩展
模拟真实用户操作流程,避免被平台检测为机器人
import os
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
class TaobaoBatchTool:
def init(self, username, password):
self.username = username
self.password = password
self.driver = None
self.wait_time = 10
self.init_driver()
def init_driver(self):
"""初始化浏览器驱动"""
options = webdriver.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('--start-maximized')
self.driver = webdriver.Chrome(options=options)
self.driver.implicitly_wait(self.wait_time)
def login(self):
"""登录淘宝卖家中心"""
try:
self.driver.get('https://login.taobao.com/')
WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.ID, 'fm-login-id'))
).send_keys(self.username)
self.driver.find_element(By.ID, 'fm-login-password').send_keys(self.password)
self.driver.find_element(By.CSS_SELECTOR, '.fm-button.fm-submit.password-login').click()
# 等待登录成功
WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.LINK_TEXT, '卖家中心'))
)
print("登录成功")
return True
except Exception as e:
print(f"登录失败: {str(e)}")
return False
def batch_upload_products(self, product_file):
"""批量上传商品"""
try:
products = pd.read_excel(product_file)
self.driver.get('https://sell.taobao.com/auction/merchandise/auction_list.htm')
for index, row in products.iterrows():
try:
# 点击发布商品按钮
WebDriverWait(self.driver, self.wait_time).until(
EC.element_to_be_clickable((By.LINK_TEXT, '发布商品'))
).click()
# 选择商品类目
WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.ID, 'J_Category'))
).click()
# 填写商品信息
self._fill_product_info(row)
# 提交商品
self.driver.find_element(By.ID, 'J_Submit').click()
print(f"成功上传商品: {row['title']}")
time.sleep(2) # 防止操作过快
except Exception as e:
print(f"上传商品 {row['title']} 失败: {str(e)}")
continue
return True
except Exception as e:
print(f"批量上传商品失败: {str(e)}")
return False
def _fill_product_info(self, product):
"""填写商品详细信息"""
# 商品标题
self.driver.find_element(By.ID, 'J_Title').send_keys(product['title'])
# 商品价格
self.driver.find_element(By.ID, 'J_Price').send_keys(str(product['price']))
# 商品库存
self.driver.find_element(By.ID, 'J_Quantity').send_keys(str(product['quantity']))
# 商品描述
self.driver.switch_to.frame('J_DescIframe')
self.driver.find_element(By.TAG_NAME, 'body').send_keys(product['description'])
self.driver.switch_to.default_content()
# 上传主图
for img in product['images'].split(','):
self.driver.find_element(By.CSS_SELECTOR, '.uploader-pick').send_keys(os.path.abspath(img.strip()))
time.sleep(1)
def batch_list_products(self, product_ids):
"""批量上架商品"""
try:
self.driver.get('https://sell.taobao.com/auction/merchandise/auction_list.htm')
for product_id in product_ids:
try:
# 搜索商品
search_box = WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.ID, 'search-key'))
)
search_box.clear()
search_box.send_keys(product_id)
search_box.send_keys(Keys.RETURN)
# 勾选商品
WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.CSS_SELECTOR, f'input[value="{product_id}"]'))
).click()
# 点击上架按钮
self.driver.find_element(By.LINK_TEXT, '上架').click()
print(f"成功上架商品ID: {product_id}")
time.sleep(1)
except Exception as e:
print(f"上架商品ID {product_id} 失败: {str(e)}")
continue
return True
except Exception as e:
print(f"批量上架商品失败: {str(e)}")
return False
def batch_ship_orders(self, order_file):
"""批量发货"""
try:
orders = pd.read_excel(order_file)
self.driver.get('https://trade.taobao.com/trade/itemlist/list_sold_items.htm')
for index, row in orders.iterrows():
try:
# 搜索订单
search_box = WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.ID, 'search-order-input'))
)
search_box.clear()
search_box.send_keys(row['order_id'])
search_box.send_keys(Keys.RETURN)
# 勾选订单
WebDriverWait(self.driver, self.wait_time).until(
EC.presence_of_element_located((By.CSS_SELECTOR, f'input[value="{row["order_id"]}"]'))
).click()
# 点击发货按钮
self.driver.find_element(By.LINK_TEXT, '发货').click()
# 填写物流信息
self._fill_shipping_info(row)
# 确认发货
self.driver.find_element(By.ID, 'J_Confirm').click()
print(f"成功发货订单: {row['order_id']}")
time.sleep(1)
except Exception as e:
print(f"发货订单 {row['order_id']} 失败: {str(e)}")
continue
return True
except Exception as e:
print(f"批量发货失败: {str(e)}")
return False
def _fill_shipping_info(self, order):
"""填写物流信息"""
# 选择物流公司
self.driver.find_element(By.CSS_SELECTOR, '.logistics-company').click()
self.driver.find_element(By.XPATH, f"//li[contains(text(), '{order['shipping_company']}')]").click()
# 填写运单号
self.driver.find_element(By.ID, 'J_LogisticCode').send_keys(order['tracking_number'])
def close(self):
"""关闭浏览器"""
if self.driver:
self.driver.quit()
def main():
# 示例用法
tool = TaobaoBatchTool('your_username', 'your_password')
try:
if tool.login():
# 批量上传商品
tool.batch_upload_products('products.xlsx')
# 批量上架商品
product_ids = ['123456', '789012']
tool.batch_list_products(product_ids)
# 批量发货
tool.batch_ship_orders('orders.xlsx')
finally:
tool.close()
if name == 'main':
main()