个人使用
- User
个人使用
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
个人使用
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
以下是一个更适合个人使用的京东店铺巡店脚本,使用Selenium模拟浏览器操作,更稳定且不易被反爬:
import time
import pandas as pd
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
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import re
class JDShopCrawler:
def __init__(self):
# 配置Chrome选项
options = webdriver.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
self.driver = webdriver.Chrome(options=options)
self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
self.wait = WebDriverWait(self.driver, 10)
def get_shop_id(self, shop_url):
"""从店铺URL提取店铺ID"""
match = re.search(r'index-(\d+)', shop_url)
if match:
return match.group(1)
return None
def get_all_products(self, shop_url):
"""获取店铺所有商品"""
shop_id = self.get_shop_id(shop_url)
if not shop_id:
print("无法解析店铺ID")
return []
# 访问店铺商品列表页
search_url = f"https://mall.jd.com/view_search-{shop_id}.html"
self.driver.get(search_url)
time.sleep(3)
products = []
page = 1
while True:
print(f"正在抓取第 {page} 页...")
# 等待商品加载
try:
self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "jSearchListArea")))
except TimeoutException:
print("页面加载超时")
break
# 滚动页面以加载所有商品
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
# 获取当前页所有商品
items = self.driver.find_elements(By.CSS_SELECTOR, ".jSearchListArea li")
for item in items:
try:
# 获取商品链接
link_elem = item.find_element(By.CSS_SELECTOR, ".jDesc a")
product_url = link_elem.get_attribute("href")
if not product_url.startswith("http"):
product_url = "https:" + product_url
# 获取商品标题
title = link_elem.get_attribute("title")
products.append({
'url': product_url,
'title': title
})
except NoSuchElementException:
continue
# 检查是否有下一页
try:
next_btn = self.driver.find_element(By.CSS_SELECTOR, ".next")
if "disabled" in next_btn.get_attribute("class"):
break
next_btn.click()
page += 1
time.sleep(3)
except NoSuchElementException:
break
return products
def get_product_details(self, product_url):
"""获取商品详情和SKU信息"""
self.driver.get(product_url)
time.sleep(3)
sku_info = []
try:
# 获取商品标题
title = self.driver.find_element(By.CSS_SELECTOR, ".sku-name").text.strip()
# 获取价格
try:
price = self.driver.find_element(By.CSS_SELECTOR, ".price.J-p-" + product_url.split("/")[-1].split(".")[0]).text
except:
price = "价格获取失败"
# 获取SKU选项
sku_items = self.driver.find_elements(By.CSS_SELECTOR, "#choose-attrs .item")
if sku_items:
# 遍历每个SKU属性
for sku_group in sku_items:
sku_options = sku_group.find_elements(By.CSS_SELECTOR, "a")
for option in sku_options:
sku_name = option.get_attribute("title") or option.text.strip()
# 点击SKU获取对应价格
try:
option.click()
time.sleep(1)
# 重新获取价格
current_price = self.driver.find_element(By.CSS_SELECTOR, ".price.J-p-" + product_url.split("/")[-1].split(".")[0]).text
sku_info.append({
'sku_name': sku_name,
'price': current_price
})
except:
sku_info.append({
'sku_name': sku_name,
'price': price
})
else:
# 没有SKU选项的商品
sku_info.append({
'sku_name': '默认规格',
'price': price
})
return title, sku_info
except Exception as e:
print(f"获取商品详情失败: {e}")
return None, []
def crawl_shop(self, shop_url):
"""爬取整个店铺"""
print("开始获取店铺商品列表...")
products = self.get_all_products(shop_url)
print(f"共找到 {len(products)} 个商品")
all_data = []
for i, product in enumerate(products, 1):
print(f"正在处理第 {i}/{len(products)} 个商品: {product['title'][:30]}...")
title, sku_info = self.get_product_details(product['url'])
if title and sku_info:
for sku in sku_info:
all_data.append({
'商品链接': product['url'],
'商品标题': title,
'SKU名称': sku['sku_name'],
'到手价': sku['price']
})
# 避免请求过快
time.sleep(2)
return all_data
def save_to_excel(self, data, filename='京东店铺商品数据.xlsx'):
"""保存数据到Excel"""
df = pd.DataFrame(data)
df.to_excel(filename, index=False, engine='openpyxl')
print(f"\n数据已保存到 {filename}")
print(f"共保存 {len(data)} 条数据")
def close(self):
"""关闭浏览器"""
self.driver.quit()
def main():
# 使用示例
shop_url = input("请输入京东店铺链接(如:https://mall.jd.com/index-1000000127.html): ")
crawler = JDShopCrawler()
try:
# 爬取数据
data = crawler.crawl_shop(shop_url)
# 保存到Excel
if data:
crawler.save_to_excel(data)
else:
print("未获取到任何数据")
finally:
crawler.close()
if __name__ == "__main__":
main()
pip install selenium pandas openpyxl
下载ChromeDriver:
运行脚本:
python jd_shop_crawler.py