当前位置: 首页 > 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爬取天猫商品数据。在实际应用中,需要根据目标网站的具体情况调整代码,并注意遵守相关法律法规和网站规则。希望本教程对你有所帮助!

相关文章:

  • WireShark相关技巧
  • Python 入门到进阶全指南:从语言特性到实战项目
  • DexUMI:以人手为通用操作界面,实现灵巧操作
  • 【android bluetooth 协议分析 14】【HFP详解 1】【案例一: 手机侧显示来电,但车机侧没有显示来电: 讲解AT+CLCC命令】
  • 【OpenGL学习】(四)统一着色和插值着色
  • Nginx 安全设置配置
  • css实现圆环展示百分比,根据值动态展示所占比例
  • 代码随想录|动态规划|50编辑距离
  • oracle从表B更新拼接字段到表A
  • Fiddler Everywhere 安卓手机抓包
  • 一文了解 GPU 服务器及其在数据中心中的角色
  • 常见的MySQL索引类型
  • Day44打卡 @浙大疏锦行
  • MVCC理解
  • c++ STL 仿函数和适配器(算法常用)
  • Java运行环境配置日志(Log)运行条件,包含鸿蒙HarmonyOS
  • 【Java】CopyOnWriteArrayList
  • 【OSG学习笔记】Day 15: 路径动画与相机漫游
  • 结构性设计模式之Facade(外观)设计模式
  • 【二分图 图论】P9384 [THUPC 2023 决赛] 着色|普及+
  • 没有内容的网站应该怎么做/冯耀宗seo视频教程
  • 标准件做网站推广效果怎么样/为什么sem的工资都不高
  • 扬州网站制作/个人网站制作多少钱
  • 汨罗住房和城乡建设局网站/百度一下官网首页登录
  • seo排名赚app下载/福州seo快速排名软件
  • 做模式网站/重庆seo海洋qq