读取douban_books.html文件,提取书籍如下信息:标题,作者,出版年份,出版社;并将其打印出来。 使用sqlite3数据库工具,创建数据库book.db,在数据库中创建表格book。 将提取出来的书籍信息,存入数据库表格book中,并将书籍信息打印出来。
时间: 2024-03-14 16:46:55 浏览: 101
好的,我可以完成你的要求。首先,需要安装BeautifulSoup4和lxml库,用于解析HTML文件。可以使用以下命令进行安装:
```
pip install beautifulsoup4 lxml
```
然后,我将使用以下Python代码提取书籍信息:
```python
from bs4 import BeautifulSoup
import sqlite3
# 打开HTML文件
with open('douban_books.html', 'r', encoding='utf-8') as f:
html = f.read()
# 解析HTML文件
soup = BeautifulSoup(html, 'lxml')
# 获取所有书籍的信息
books = []
for book in soup.find_all('li', class_='subject-item'):
title = book.find('h2').a['title']
author = book.find('div', class_='pub').get_text().split('/')[0].strip()
year = book.find('div', class_='pub').get_text().split('/')[-3].strip()
press = book.find('div', class_='pub').get_text().split('/')[-2].strip()
books.append((title, author, year, press))
# 打印提取的书籍信息
for book in books:
print('标题:', book[0])
print('作者:', book[1])
print('出版年份:', book[2])
print('出版社:', book[3])
print()
# 连接到数据库
conn = sqlite3.connect('book.db')
c = conn.cursor()
# 创建book表格
c.execute('''CREATE TABLE book
(title text, author text, year text, press text)''')
# 插入书籍信息
for book in books:
c.execute("INSERT INTO book VALUES (?, ?, ?, ?)", book)
# 提交更改并关闭连接
conn.commit()
conn.close()
```
代码中,我使用BeautifulSoup4库解析HTML文件,并通过find_all方法获取所有书籍的信息。然后,将书籍信息存储在books列表中,并通过循环打印每本书的信息。接着,我使用sqlite3库连接到数据库,并创建名为book的表格。然后,将提取的书籍信息插入到表格中,并通过commit方法提交更改。最后,关闭数据库连接。