爬取书籍信息通常涉及以下步骤:
获取网页源代码:
使用`requests`库发送HTTP请求获取网页内容。
解析HTML:
使用`BeautifulSoup`库解析HTML内容。
提取数据:
通过解析后的HTML提取书籍信息,如书名、作者、封面、简介等。
存储数据:
将提取的数据保存到数据库或写入本地文件。
下面是一个简单的示例代码,展示了如何使用Python爬取书籍信息:

```python
import requests
from bs4 import BeautifulSoup
import pymysql
定义获取网页内容的函数
def get_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
return response.text
定义提取书籍信息的函数
def extract_books(html):
soup = BeautifulSoup(html, 'html.parser')
books = []
for book in soup.find_all('div', class_='book'):
title = book.find('h2').text
author = book.find('span', class_='author').text
cover = book.find('img')['src']
summary = book.find('p', class_='summary').text
books.append({'title': title, 'author': author, 'cover': cover, 'summary': summary})
return books
定义将书籍信息存入数据库的函数
def save_to_db(books):
conn = pymysql.connect(host='localhost', user='root', password='password', db='books', charset='utf8mb4')
cursor = conn.cursor()
insert_query = "INSERT INTO books (title, author, cover, summary) VALUES (%s, %s, %s, %s)"
cursor.executemany(insert_query, books)
conn.commit()
conn.close()
主程序
if __name__ == '__main__':
url = 'https://example.com/books' 替换为实际的书籍网站URL
html = get_html(url)
books = extract_books(html)
save_to_db(books)
请注意,实际使用时需要根据目标网站的具体结构修改代码中的选择器和数据库连接信息。同时,确保遵循网站的`robots.txt`文件规定以及任何相关的法律法规。
