python爬取京东商品信息存入数据库
时间: 2025-01-15 17:10:23 浏览: 64
### 使用Python实现网页爬虫抓取京东商品详情并保存至SQL数据库
#### 准备工作
为了完成此任务,需安装必要的库。可以利用`pip install requests beautifulsoup4 pymysql selenium`命令来安装所需的包。
#### 抓取页面信息
通过发送HTTP请求获取目标网页的内容是第一步操作。对于动态加载内容较多的页面,如京东的商品列表页,可能还需要借助Selenium模拟浏览器行为以确保能够获得完整的HTML文档[^2]。
```python
import requests
from bs4 import BeautifulSoup
url = 'https://example.jd.com' # 替换为目标URL
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
else:
print('Failed to retrieve the page.')
```
#### 解析所需数据
一旦获得了响应体中的HTML源码,则可运用BeautifulSoup解析器提取感兴趣的信息片段,比如产品名称、价格等字段。
```python
items = []
for item in soup.find_all('div', class_='gl-i-wrap'): # 假设这是包含单个产品的容器标签
name = item.select_one('.p-name').get_text(strip=True)
price = float(item.select_one('.p-price i').text.strip())
items.append({
'name': name,
'price': price
})
```
#### 数据入库前准备
建立与MySQL服务器之间的连接,并定义好要执行的操作语句模板;这里假设已经有一个名为`products`的数据表用于接收这些记录。
```sql
CREATE TABLE IF NOT EXISTS products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
price DECIMAL(10 , 2 )
);
```
#### 插入数据到数据库
最后一步就是把之前收集好的每条记录逐一写入关系型数据库中去,在这过程中要注意防止SQL注入攻击以及处理可能出现的各种异常情况。
```python
import pymysql.cursors
connection = pymysql.connect(
host='localhost',
user='root',
password='',
database='testdb',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
sql = """INSERT INTO `products` (`name`, `price`) VALUES (%s,%s)"""
for product_info in items:
try:
cursor.execute(sql,(product_info['name'], product_info['price']))
except Exception as e:
print(f"Error inserting {product_info}: ", str(e))
connection.commit()
finally:
connection.close()
```
阅读全文
相关推荐


















