Python爬取当当网图书数据并存储到MySQL数据库
以下是一个简单的爬取当当网图书信息并存储到MySQL数据库中的示例代码:
import requests
from bs4 import BeautifulSoup
import pymysql
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='dangdang', charset='utf8')
cursor = conn.cursor()
# 爬取图书信息
url = 'http://category.dangdang.com/cp01.54.00.00.00.00.html'
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)
soup = BeautifulSoup(response.text, 'html.parser')
books = soup.select('.bigimg .pic')
# 解析图书信息并存储到数据库中
for book in books:
name = book['title']
href = book['href']
img = book.find('img')['src']
price = book.select('.price_n')[0].text.strip('¥')
sql = 'INSERT INTO books (name, href, img, price) VALUES (%s, %s, %s, %s)'
cursor.execute(sql, (name, href, img, price))
# 提交事务并关闭数据库连接
conn.commit()
cursor.close()
conn.close()
这个示例爬取当当网的图书信息,并将图书名、链接、图片、价格存储到MySQL数据库中。需要注意的是,这个示例只爬取了一页的图书信息,如果需要爬取多页的数据,需要修改URL并进行循环爬取。此外,这个示例只爬取了图书信息,如果需要爬取其他商品信息,需要修改代码中的选择器。
原文地址: https://www.cveoy.top/t/topic/mWXg 著作权归作者所有。请勿转载和采集!