Python爬取天猫商品数据详细教程
一、前期准备
1. 环境配置
- Python环境 :确保已安装Python 3.x版本,建议使用Anaconda或直接从Python官网下载安装。
- 第三方库 :
requests
:用于发送HTTP请求。BeautifulSoup
:用于解析HTML内容。lxml
:作为BeautifulSoup的解析器,提高解析效率。selenium
(可选):用于处理动态加载的内容。pandas
(可选):用于数据处理和存储。
安装命令:
bash
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请求,获取页面内容。
python
import requests
url = '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内容,提取商品信息。
python
import requests
url = '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
模拟浏览器行为。
python
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文件
python
import pandas as pd
data = {
'商品标题': [title],
'商品价格': [price],
'商品销量': [sales]
}
df = pd.DataFrame(data)
df.to_csv('tmall_products.csv', index=False, encoding='utf-8-sig')
保存到数据库(以MySQL为例)
python
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的规律,通过循环实现。
python
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.text
soup = 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。
python
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结构变化等情况。
python
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # 如果响应状态码不是200,抛出HTTPError异常
html_content = response.text
soup = BeautifulSoup(html_content, 'lxml')
# 提取商品信息...
except requests.exceptions.RequestException as e:
print(f"请求发生错误:{e}")
except Exception as e:
print(f"发生未知错误:{e}")
四、完整代码示例
python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import random
def 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.text
soup = 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 None
except Exception as e:
print(f"发生未知错误:{e}")
return None
def main():
# 示例:爬取单个商品
product_url = 'https://detail.tmall.com/item.htm?id=商品ID' # 替换为实际的商品ID
product_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爬取天猫商品数据。在实际应用中,需要根据目标网站的具体情况调整代码,并注意遵守相关法律法规和网站规则。希望本教程对你有所帮助!