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('电子词典数据库生成完毕')

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田无水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值