Python爬虫+BeautifulSoup+SQLite3:从网页抓取数据并存储到数据库
该代码使用Python爬虫技术,从网页'http://49.235.120.214/sunzhiwei/index.html'中提取自我介绍信息,并使用BeautifulSoup库解析HTML结构,最后将提取到的信息存储到SQLite3数据库中。
代码首先使用requests库获取网页内容,并使用BeautifulSoup解析HTML结构。然后,通过find_all方法查找所有包含class为'introduction'的<p>标签,并提取它们的文本内容。
接着,代码创建了一个名为'胡芸人'的SQLite3数据库表,并将提取到的信息插入到该表中。最后,代码查询数据库表中的所有数据并打印出来。
该代码的运行结果为:
['姓名:胡芸宁
家乡:北京
课程建议:学习Python编程和数据分析']
插入了1条记录
(1, '姓名:胡芸宁', '家乡:北京', '课程建议:学习Python编程和数据分析')
该结果表明,代码成功从网页抓取了一条自我介绍信息,并将其存储到SQLite3数据库中。
代码示例:
import requests
from bs4 import BeautifulSoup
import sqlite3
# 爬取网页
url = 'http://49.235.120.214/sunzhiwei/index.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763'
}
codes = requests.get(url, headers=headers).text
# 用BeautifulSoup解析网页并获取所有p标签的内容
soup = BeautifulSoup(codes, 'html.parser')
# 获取每个p标签中的自我介绍内容
p_tags_content = [tag.text for tag in soup.find_all('p', class_='introduction')]
print(p_tags_content)
# 创建一个自我介绍表,表名为“胡芸宁”
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
sql = 'CREATE TABLE 胡芸人(id INTEGER PRIMARY KEY, name TEXT, hometown TEXT, course_recommendation TEXT)'
cursor.execute(sql)
# 将爬取到的自我介绍数据插入到“胡芸人”表中
for index, content in enumerate(p_tags_content, start=1):
name = content[0].strip() # 假设自我介绍的第一行是姓名
hometown = content[1].strip() # 假设自我介绍的第二行是家乡介绍
course_recommendation = content[2].strip() # 假设自我介绍的第三行是课程建议
sql = f'INSERT INTO 胡芸人 VALUES ({index}, ?, ?, ?)'
cursor.execute(sql, (name, hometown, course_recommendation))
conn.commit()
print(f'插入了{len(p_tags_content)}条记录')
# 重新连接到数据库
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
# 查询“胡芸人”表中的所有数据
cursor.execute('SELECT * FROM 胡芸人')
rows = cursor.fetchall()
# 打印所有行
for row in rows:
print(row)
原文地址: https://www.cveoy.top/t/topic/pdf7 著作权归作者所有。请勿转载和采集!