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. 有了人工智能并不意味着基础的编程知识不重要了,相反基础知识更加重要了。人工智能大模子可以辅助我们生成代码,而我们则可以对代码举行调试,选取合适的代码,并对于冗余的代码举行综合判断,最终删除不须要的代码,使我们的代码更精减和健壮。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |