栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python抓取网页数据,并存储到sqlite中

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python抓取网页数据,并存储到sqlite中

注:代码来源于鸿蒙开发视频,经测试无误

一、安装python3.13,过

二、安装python对应的库

如requests、bs4、lxml

三、步骤解析

1、网页分析

2、获取网页文字

3、创建本地空数据库文件

4、将抓取的网页文字写入数据库

四、代码汇总

import requests
import re

words={}
def add_word(word_line):
    global words
    #用词性作为分隔符分隔字符串
    result1=re.split('[a-z]+.',word_line)
    pattern=re.compile('[a-z]+.')    
    #搜索所有词性
    result2=pattern.findall(word_line)
    #得到单词
    word=result1[0].strip()
    #保存单词的解释,以词性作为key,解释作为Value
    meanings={}
    for i in range(0,len(result2)):
        key=result2[i].strip()
        value=result1[i+1].strip()
        meanings[key]=value
    words[word]=meanings

r=requests.get('https://www.eol.cn/html/en/cetwords/cet4.shtml')
html=r.content
html_doc=str(html,'utf-8')
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')
tags=soup.find_all(attrs={'class':'wordL fl'})
for tag in tags:
    p_list=tag.select('p')
    for p in p_list:
        add_word(p.text)

print(words)#得到一长串数据,暂不解析
print('单词抓取完毕')

####生成本地词库######
import sqlite3
import os

db_path='d://dict.sqlite'#设置数据库路径
if os.path.exists(db_path):#如果数据库存在
    os.remove(db_path)#删除存在的数据库

conn=sqlite3.connect(db_path)
c=conn.cursor()
c.execute('''create table words
    (id int primary key not null,
    word varchar(30) not null,
    type varchar(10) not null,
    meanings text not null);''')
c.execute('create index word_index on words(word)')
conn.commit()
conn.close()
print('创建数据库成功')#创建完成一个空数据库名dict,表words

#将抓取到的数据转存到dict中
conn=sqlite3.connect(db_path)
c=conn.cursor()  
i=1
for word in words:#拆分从网页抓取到的数据
    value=words[word]
    for type in value:
        meanings=value[type]
        sql =f'insert into words(id,word,type,meanings)
        values({i},"{word}","{type}","{meanings}")';
        c.execute(sql)
        i+=1
    conn.commit()

conn.close()
print('电子词典数据库生成完毕')

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925409.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号