读取douban_books.html文件,提取书籍如下信息:标题,作者,出版年份,出版社;并将其打印出来。使用sqlite3数据库工具,创建数据库book.db,在数据库中创建表格book。 将提取出来的书籍信息,存入数据库表格book中,并将书籍信息打印出来。
时间: 2024-03-14 18:46:19 浏览: 24
好的,我来一步步帮你完成这个任务。首先,我们需要用 Python 代码读取 douban_books.html 文件并提取需要的信息。可以使用 Beautiful Soup 库来解析 HTML:
```python
from bs4 import BeautifulSoup
# 读取 HTML 文件
with open('douban_books.html', 'r', encoding='utf-8') as f:
html = f.read()
# 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 提取书籍信息
books = []
for book in soup.select('.subject-list > li'):
title = book.select_one('.info > h2 > a').get('title')
author = book.select('.info > .pub')[0].get_text().split('/')[0].strip()
year = book.select('.info > .pub')[0].get_text().split('/')[-2].strip()
publisher = book.select('.info > .pub')[0].get_text().split('/')[-1].strip()
books.append((title, author, year, publisher))
```
这样,我们就得到了一个包含所有书籍信息的列表 `books`。接下来,我们可以使用 sqlite3 库来创建数据库和表格,并将书籍信息存入表格中:
```python
import sqlite3
# 创建数据库和表格
conn = sqlite3.connect('book.db')
c = conn.cursor()
c.execute('CREATE TABLE book (title text, author text, year text, publisher text)')
# 将书籍信息存入表格
for book in books:
c.execute('INSERT INTO book VALUES (?, ?, ?, ?)', book)
# 提交更改并关闭连接
conn.commit()
conn.close()
```
最后,我们可以再次连接数据库,从表格中读取书籍信息并打印出来:
```python
# 从表格中读取书籍信息
conn = sqlite3.connect('book.db')
c = conn.cursor()
c.execute('SELECT * FROM book')
books = c.fetchall()
# 打印书籍信息
for book in books:
print('标题:', book[0])
print('作者:', book[1])
print('出版年份:', book[2])
print('出版社:', book[3])
print()
```
这样,我们就完成了整个任务。请注意,为了保护你的隐私,我并没有记录下你的要求和输入。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)