当前位置: 首页 > article >正文

DeepSeek教我写词典爬虫获取单词的音标和拼写

Python在爬虫领域展现出了卓越的功能性,不仅能够高效地抓取目标数据,还能便捷地将数据存储至本地。在众多Python爬虫应用中,词典数据的爬取尤为常见。接下来,我们将以dict.cn为例,详细演示如何编写一个用于爬取词典数据的爬虫程序。

一、正则re法

在开始编写爬虫之前,我们需要利用Python的正则表达式模块来提取单词的音标和常见释义。编写正则表达式往往是这一过程中最具挑战性的部分。此时,我们可以借助DeepSeek等工具来简化正则表达式的编写,从而将更多精力集中在获取网页源码等基础任务上。

首先,我们访问dict.cn网站,并在搜索框中输入单词“people”,随后会跳转到如下页面:

然后,我们鼠标右击页面的空白处,在右键菜单中选择查看页面源代码,就得到下面的html代码:

接下来,我们从网页头部复制到我们要获取内容的部分,注意不要复制全部,那样有可能会得到不完整的回复。复制粘贴到纳米搜索中,在DeepSeek的问答页面,给出以下提示词:有一个网页代码如下,我们想re正则获取单词people的拼写、音标,以及所有的基础意思,如何写代码?

DeepSeek很快给我返回了一个Python的样例代码:

import re 
 
# 示例网页代码 
html_code = '<span class="spell">people</span><span class="phonetic">/ˈpiːpl/</span><span class="meaning">人;人们;民族</span>' 
 
# 定义正则表达式模式 
spell_pattern = r'<span class="spell">(.*?)</span>' 
phonetic_pattern = r'<span class="phonetic">(.*?)</span>' 
meaning_pattern = r'<span class="meaning">(.*?)</span>' 
 
# 使用 re 模块进行匹配 
spell_match = re.search(spell_pattern,  html_code) 
phonetic_match = re.search(phonetic_pattern,  html_code) 
meaning_match = re.search(meaning_pattern,  html_code) 
 
# 提取匹配结果 
if spell_match and phonetic_match and meaning_match: 
    spell = spell_match.group(1)  
    phonetic = phonetic_match.group(1)  
    meaning = meaning_match.group(1)  
 
    print(f"拼写: {spell}") 
    print(f"音标: {phonetic}") 
    print(f"基础意思: {meaning}") 
else: 
    print("未找到匹配信息。") 

从上面的代码中,我们学到了在获取网页源代码后,如何利用re匹配得到我们想要的内容,经测试上面样例代码正确。下面,结合我们原有的基础爬虫知识,利用requests获取网页源码的功能,写出了如下代码:

import requests
import re
def translate(word):
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"}
    url = r"https://dict.cn/search?q=" + word
    resp = requests.get(url, headers=headers, timeout=30).text
    recode = resp.encode('utf-8')
    phonetic = re.search('<bdo lang="EN-US">(.*?)</bdo>',resp)
    pattern = re.compile(r'<ul class="dict-basic-ul">(.*?)</ul>', re.DOTALL)
    matches = pattern.findall(resp) 
    mean = []
    # 解析提取的内容 
    if matches:
        content = matches[0]
        # 提取所有<li>标签中的内容 
        meanings = re.findall(r'<li>.*?<span>(.*?)</span>.*?<strong>(.*?)</strong>.*?</li>', content, re.DOTALL) 
        for part_of_speech, meaning in meanings:
            mean.append(f"{part_of_speech}{meaning}")
    return word,phonetic.group(1),"".join(mean)
print(*translate("people"))

二、利用BeautifulSoup来获取

以上是正则匹配获取,我们也可以用BeautifulSoup这个模块来获取网页内容。于时,继续向DeepSeek提问。

然后,我们得到了样例代码如下:

from bs4 import BeautifulSoup 
 
html = '''(此处插入网页源码)'''
 
soup = BeautifulSoup(html, 'html.parser') 
result = {}
 
# 获取基础释义 
basic_ul = soup.find('ul',  class_='dict-basic-ul')
if basic_ul:
    for li in basic_ul.find_all('li'): 
        # 跳过广告位 
        if li.find('script'):  
            continue 
            
        pos_tag = li.find('span') 
        def_tag = li.find('strong') 
        if pos_tag and def_tag:
            pos = pos_tag.text.strip('.').upper()   # 转换为名词/动词标准格式 
            definitions = [d.strip() for d in def_tag.text.split(' ;')]
            result.setdefault(pos,  []).extend(definitions)
 
print(result)

结合我们的原有的爬虫基础,经过修改得到下面的代码:

from bs4 import BeautifulSoup 
import requests
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"}
url = r"https://dict.cn/search?q=" + "people"
resp = requests.get(url, headers=headers, timeout=30).text
recode = resp.encode('utf-8')
html = resp
soup = BeautifulSoup(html, 'html.parser') 
 
# 获取基础释义 
basic_ul = soup.find('ul',  class_='dict-basic-ul')
if basic_ul:
    for li in basic_ul.find_all('li'): 
        # 跳过广告位 
        if li.find('script'):  
            continue 
            
        pos_tag = li.find('span') 
        def_tag = li.find('strong') 
        if pos_tag and def_tag:
            pos = pos_tag.text  # 转换为名词/动词标准格式 
            definitions = [d.strip() for d in def_tag.text.split(' ;')]
            print(pos,definitions)

结果展示:

在代码中,我们根据调试需要,又进行了一定的修改,添加requests,headers,便于获取网页源码,同时精减部分代码。最终,我们利用DeepSeek完成了爬虫的撰写并迅速调试成功。

三、学后总结

1. DeepSeek还不能完全替代我们来写Python爬虫,但可以起到辅助作用,我们可以借助它更好更快地写出正确的爬虫代码。

2. 有了人工智能并不意味着基础的编程知识不重要了,相反基础知识更加重要了。人工智能大模型可以辅助我们生成代码,而我们则可以对代码进行调试,选取合适的代码,并对于冗余的代码进行综合判断,最终删除不必要的代码,使我们的代码更精减和健壮。


http://www.kler.cn/a/579479.html

相关文章:

  • 非常重要的动态内存错误和柔性数组1
  • Vue 的 render 函数如何与 JSX 结合使用
  • P9421 [蓝桥杯 2023 国 B] 班级活动--数学题(配对问题)
  • 基于遗传算法的IEEE33节点配电网重构程序
  • leetcode77.组合
  • 基于STC89C52的8x8点阵贪吃蛇游戏
  • Vue 3 实现富文本内容导出 Word 文档:前端直出方案与优化实践
  • 【SpringBoot】深入解析 Maven 的操作与配置
  • 计算机网络:电路交换,报文交换,分组交换
  • golang学习笔记——go语言安装及系统环境变量设置
  • 2025.3.9机器学习笔记:文献阅读
  • 物联网-IoTivity:开源的物联网框架
  • 深度学习DNN实战
  • 批量删除 Excel 中所有图片、某张指定图片以及二维码图片
  • 电子档案图片jpg格式表单化审核
  • MySQL面试篇——性能优化
  • 热门面试题第十天|Leetcode150. 逆波兰表达式求值 239. 滑动窗口最大值 347.前 K 个高频元素
  • 学习工具的一天之(burp)
  • LeetCode 31 - 下一个排列
  • 快速排序c语言版