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

打印 上一主题 下一主题

主题 1008|帖子 1008|积分 3024

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

在开始编写爬虫之前,我们需要利用Python的正则表达式模块来提取单词的音标和常见释义。编写正则表达式每每是这一过程中最具寻衅性的部分。此时,我们可以借助DeepSeek等工具来简化正则表达式的编写,从而将更多精力集中在获取网页源码等基础任务上。
起首,我们访问dict.cn网站,并在搜索框中输入单词“people”,随后会跳转到如下页面:
然后,我们鼠标右击页面的空白处,在右键菜单中选择查看页面源代码,就得到下面的html代码:

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

DeepSeek很快给我返回了一个Python的样例代码:
  1. import re
  2. # 示例网页代码
  3. html_code = '<span class="spell">people</span><span class="phonetic">/ˈpiːpl/</span><span class="meaning">人;人们;民族</span>'
  4. # 定义正则表达式模式
  5. spell_pattern = r'<span class="spell">(.*?)</span>'
  6. phonetic_pattern = r'<span class="phonetic">(.*?)</span>'
  7. meaning_pattern = r'<span class="meaning">(.*?)</span>'
  8. # 使用 re 模块进行匹配
  9. spell_match = re.search(spell_pattern,  html_code)
  10. phonetic_match = re.search(phonetic_pattern,  html_code)
  11. meaning_match = re.search(meaning_pattern,  html_code)
  12. # 提取匹配结果
  13. if spell_match and phonetic_match and meaning_match:
  14.     spell = spell_match.group(1)  
  15.     phonetic = phonetic_match.group(1)  
  16.     meaning = meaning_match.group(1)  
  17.     print(f"拼写: {spell}")
  18.     print(f"音标: {phonetic}")
  19.     print(f"基础意思: {meaning}")
  20. else:
  21.     print("未找到匹配信息。")
复制代码
从上面的代码中,我们学到了在获取网页源代码后,如何利用re匹配得到我们想要的内容,经测试上面样例代码正确。下面,联合我们原有的基础爬虫知识,利用requests获取网页源码的功能,写出了如下代码:
  1. import requests
  2. import re
  3. def translate(word):
  4.     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"}
  5.     url = r"https://dict.cn/search?q=" + word
  6.     resp = requests.get(url, headers=headers, timeout=30).text
  7.     recode = resp.encode('utf-8')
  8.     phonetic = re.search('<bdo lang="EN-US">(.*?)</bdo>',resp)
  9.     pattern = re.compile(r'<ul class="dict-basic-ul">(.*?)</ul>', re.DOTALL)
  10.     matches = pattern.findall(resp)
  11.     mean = []
  12.     # 解析提取的内容
  13.     if matches:
  14.         content = matches[0]
  15.         # 提取所有<li>标签中的内容
  16.         meanings = re.findall(r'<li>.*?<span>(.*?)</span>.*?<strong>(.*?)</strong>.*?</li>', content, re.DOTALL)
  17.         for part_of_speech, meaning in meanings:
  18.             mean.append(f"{part_of_speech}{meaning}")
  19.     return word,phonetic.group(1),"".join(mean)
  20. print(*translate("people"))
复制代码
二、利用BeautifulSoup来获取

以上是正则匹配获取,我们也可以用BeautifulSoup这个模块来获取网页内容。于时,继承向DeepSeek提问。
然后,我们得到了样例代码如下:
  1. from bs4 import BeautifulSoup
  2. html = '''(此处插入网页源码)'''
  3. soup = BeautifulSoup(html, 'html.parser')
  4. result = {}
  5. # 获取基础释义
  6. basic_ul = soup.find('ul',  class_='dict-basic-ul')
  7. if basic_ul:
  8.     for li in basic_ul.find_all('li'):
  9.         # 跳过广告位
  10.         if li.find('script'):  
  11.             continue
  12.             
  13.         pos_tag = li.find('span')
  14.         def_tag = li.find('strong')
  15.         if pos_tag and def_tag:
  16.             pos = pos_tag.text.strip('.').upper()   # 转换为名词/动词标准格式
  17.             definitions = [d.strip() for d in def_tag.text.split(' ;')]
  18.             result.setdefault(pos,  []).extend(definitions)
  19. print(result)
复制代码
联合我们的原有的爬虫基础,经过修改得到下面的代码:
  1. from bs4 import BeautifulSoup
  2. import requests
  3. 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"}
  4. url = r"https://dict.cn/search?q=" + "people"
  5. resp = requests.get(url, headers=headers, timeout=30).text
  6. recode = resp.encode('utf-8')
  7. html = resp
  8. soup = BeautifulSoup(html, 'html.parser')
  9. # 获取基础释义
  10. basic_ul = soup.find('ul',  class_='dict-basic-ul')
  11. if basic_ul:
  12.     for li in basic_ul.find_all('li'):
  13.         # 跳过广告位
  14.         if li.find('script'):  
  15.             continue
  16.             
  17.         pos_tag = li.find('span')
  18.         def_tag = li.find('strong')
  19.         if pos_tag and def_tag:
  20.             pos = pos_tag.text  # 转换为名词/动词标准格式
  21.             definitions = [d.strip() for d in def_tag.text.split(' ;')]
  22.             print(pos,definitions)
复制代码
结果展示:

在代码中,我们根据调试需要,又举行了肯定的修改,添加requests,headers,便于获取网页源码,同时精减部分代码。最终,我们利用DeepSeek完成了爬虫的撰写并敏捷调试乐成。
三、学后总结

1. DeepSeek还不能完全替代我们来写Python爬虫,但可以起到辅助作用,我们可以借助它更好更快地写出正确的爬虫代码。
2. 有了人工智能并不意味着基础的编程知识不重要了,相反基础知识更加重要了。人工智能大模子可以辅助我们生成代码,而我们则可以对代码举行调试,选取合适的代码,并对于冗余的代码举行综合判断,最终删除不须要的代码,使我们的代码更精减和健壮。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

火影

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表