当前位置: 首页 > news >正文

Python爬虫爬取天猫商品数据,详细教程【Python经典实战项目】

Python爬取天猫商品数据详细教程

一、前期准备

1. 环境配置

  • Python环境:确保已安装Python 3.x版本,建议使用Anaconda或直接从Python官网下载安装。
  • 第三方库
    • requests:用于发送HTTP请求。
    • BeautifulSoup:用于解析HTML内容。
    • lxml:作为BeautifulSoup的解析器,提高解析效率。
    • selenium(可选):用于处理动态加载的内容。
    • pandas(可选):用于数据处理和存储。

安装命令:

pip install requests beautifulsoup4 lxml selenium pandas
2. 了解天猫的反爬机制

天猫等电商平台通常有完善的反爬虫机制,包括但不限于:

  • User-Agent检测:检查请求头中的User-Agent字段。
  • IP限制:频繁请求可能导致IP被封禁。
  • 验证码:部分操作可能需要输入验证码。
  • 动态加载:部分内容通过JavaScript动态加载。

二、爬取天猫商品数据的基本步骤

1. 分析目标页面

  • 打开天猫商品页面:在浏览器中打开天猫商品详情页,右键选择“检查”或按F12打开开发者工具。
  • 查看网络请求:在开发者工具的“Network”选项卡中,刷新页面,查看请求的URL和响应内容。
  • 定位数据:找到包含商品信息的HTML元素,记录其标签名、类名或ID。

2. 发送HTTP请求

使用requests库发送HTTP请求,获取页面内容。

import requestsurl = 'https://detail.tmall.com/item.htm?id=商品ID'  # 替换为实际的商品ID
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}response = requests.get(url, headers=headers)
if response.status_code == 200:html_content = response.text
else:print(f"请求失败,状态码:{response.status_code}")
3. 解析HTML内容

使用BeautifulSoup解析HTML内容,提取商品信息。

import requestsurl = 'https://detail.tmall.com/item.htm?id=商品ID'  # 替换为实际的商品ID
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}response = requests.get(url, headers=headers)
if response.status_code == 200:html_content = response.text
else:print(f"请求失败,状态码:{response.status_code}")


4. 处理动态加载的内容(可选)

如果商品信息是通过JavaScript动态加载的,可以使用selenium模拟浏览器行为。

from selenium import webdriver
from selenium.webdriver.common.by import By
import time# 配置ChromeDriver路径
driver_path = 'path/to/chromedriver'  # 替换为实际的ChromeDriver路径
driver = webdriver.Chrome(executable_path=driver_path)driver.get(url)
time.sleep(5)  # 等待页面加载完成# 提取动态加载的内容(示例:提取商品标题)
title_element = driver.find_element(By.CSS_SELECTOR, 'span.J_TSearch_Title')
title = title_element.text.strip()print(f"商品标题:{title}")# 关闭浏览器
driver.quit()


5. 存储数据

将爬取的数据保存到本地文件或数据库中。

保存到CSV文件
import pandas as pddata = {'商品标题': [title],'商品价格': [price],'商品销量': [sales]
}df = pd.DataFrame(data)
df.to_csv('tmall_products.csv', index=False, encoding='utf-8-sig')

保存到数据库(以MySQL为例)
import pymysql# 连接数据库
conn = pymysql.connect(host='localhost',user='username',password='password',database='database_name',charset='utf8mb4'
)cursor = conn.cursor()# 创建表(如果不存在)
cursor.execute('''
CREATE TABLE IF NOT EXISTS tmall_products (id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(255),price VARCHAR(50),sales VARCHAR(50)
)
''')# 插入数据
sql = '''
INSERT INTO tmall_products (title, price, sales)
VALUES (%s, %s, %s)
'''
cursor.execute(sql, (title, price, sales))# 提交事务
conn.commit()# 关闭连接
cursor.close()
conn.close()

三、高级技巧与注意事项

1. 处理分页

如果需要爬取多页商品数据,可以分析分页URL的规律,通过循环实现。

base_url = 'https://list.tmall.com/search_product.htm?q=关键词&s='  # 替换为实际的搜索关键词for page in range(0, 100, 44):  # 每页44个商品,假设爬取前3页url = f"{base_url}{page}"response = requests.get(url, headers=headers)if response.status_code == 200:html_content = response.textsoup = BeautifulSoup(html_content, 'lxml')# 提取当前页的商品信息(示例:提取商品标题)product_tags = soup.find_all('div', class_='product')for product in product_tags:title_tag = product.find('a', class_='product-title')if title_tag:title = title_tag.get_text().strip()print(f"商品标题:{title}")
2. 使用代理IP

为了避免IP被封禁,可以使用代理IP。

proxies = {'http': 'http://your_proxy_ip:port','https': 'https://your_proxy_ip:port'
}response = requests.get(url, headers=headers, proxies=proxies)
3. 遵守法律法规和网站规则
  • 遵守robots.txt协议:在爬取前,检查目标网站的robots.txt文件,确保爬取行为符合网站规定。
  • 合理设置请求间隔:避免频繁请求,给服务器造成过大压力。
  • 不侵犯隐私:确保爬取的数据不涉及用户隐私。

4. 异常处理

在实际应用中,应添加异常处理机制,以应对网络请求失败、HTML结构变化等情况。

try:response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()  # 如果响应状态码不是200,抛出HTTPError异常html_content = response.textsoup = BeautifulSoup(html_content, 'lxml')# 提取商品信息...except requests.exceptions.RequestException as e:print(f"请求发生错误:{e}")
except Exception as e:print(f"发生未知错误:{e}")
四、完整代码示例
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import randomdef crawl_tmall_product(url):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}try:response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()html_content = response.textsoup = BeautifulSoup(html_content, 'lxml')# 提取商品标题title_tag = soup.find('span', class_='J_TSearch_Title')title = title_tag.get_text().strip() if title_tag else '未找到商品标题'# 提取商品价格price_tag = soup.find('span', class_='tm-price')price = price_tag.get_text().strip() if price_tag else '未找到商品价格'# 提取商品销量(以月销为例)sales_tag = soup.find('div', class_='tm-detail-hd-sale')sales = sales_tag.find('span').get_text().strip().replace('月销', '') if sales_tag else '未找到商品销量'return {'商品标题': title,'商品价格': price,'商品销量': sales}except requests.exceptions.RequestException as e:print(f"请求发生错误:{e}")return Noneexcept Exception as e:print(f"发生未知错误:{e}")return Nonedef main():# 示例:爬取单个商品product_url = 'https://detail.tmall.com/item.htm?id=商品ID'  # 替换为实际的商品IDproduct_data = crawl_tmall_product(product_url)if product_data:print(f"商品标题:{product_data['商品标题']}")print(f"商品价格:{product_data['商品价格']}")print(f"商品销量:{product_data['商品销量']}")# 保存到CSV文件data = [product_data]df = pd.DataFrame(data)df.to_csv('tmall_products.csv', index=False, encoding='utf-8-sig')print("数据已保存到tmall_products.csv")if __name__ == '__main__':main()
五、总结

通过以上步骤,你可以使用Python爬取天猫商品数据。在实际应用中,需要根据目标网站的具体情况调整代码,并注意遵守相关法律法规和网站规则。希望本教程对你有所帮助!

http://www.xdnf.cn/news/877429.html

相关文章:

  • VBA中类的解读及应用第二十四讲:把源数据赋给类利用类完成查找
  • 【AI News | 20250604】每日AI进展
  • Markdown基础(1.2w字)
  • OPC UA 知识概述
  • 行业年终工作总结汇报PPT模版分享
  • 并发编程的问题与管程
  • LangChain深度解析:LLM应用开发利器
  • Redis常见使用场景解析
  • 【C语言个数最大最多】2022-4-1
  • 网络攻防技术十二:社会工程学
  • Mysql选择合适的字段创建索引
  • Java Lombok @Data 注解用法详解
  • 量子通信:从科幻走向现实的未来通信技术
  • 四、Sqoop 导入表数据子集
  • 使用C++调用python库
  • 东西方艺术的对话:彰显中国传统艺术之美与价值
  • 主流Agent开发平台学习笔记:扣子罗盘coze loop 功能拆解
  • Vue插件
  • 租物理服务器,如何避开 “高价陷阱”
  • MES管理系统的核心数据采集方式有哪些
  • Linux 环境下 PPP 拨号的嵌入式开发实现
  • CMake在VS中使用远程调试
  • python实现合并多个dot文件
  • linux系统--iptables实战案例
  • 在本地电脑中部署阿里 Qwen3 大模型及连接到 Elasticsearch
  • if(!p)等价于 if(p==0)
  • 【学习笔记】Python金融基础
  • 猎板硬金镀层厚度:新能源汽车高压系统的可靠性基石
  • 压测软件-Jmeter
  • socket是什么