Beautiful爬取海词网词汇意思和短语
直接上代码
# -*- encoding:utf-8 -*-
import urllib.request # 导入urllib库的request模块
from bs4 import BeautifulSoup
import lxml #文档解析器
import os #os模块就是对操作系统进行操作
import numpy as np #列表、字典、字符串等中计算元素重复的次数
urls=[]
titles=[]
target=input("请输入你要查询的单词")
#爬取所有新闻的url和标题,存储在urls和titles中,这里range(1)表示只爬取1页。
for i in range(1):
url='http://dict.cn//'+target
res = urllib.request.urlopen(url) #调用urlopen()从服务器获取网页响应(respone),其返回的响应是一个实例
html = res.read().decode('utf-8') #调用返回响应示例中的read(),utf-8解码,可以读取html
soup = BeautifulSoup(html, 'lxml')
result = soup.find_all('div',attrs={'class': ['section def','layout coll']})
download_soup = BeautifulSoup(str(result), 'lxml')
ol = download_soup.find_all('ol',slider="2")
lt=[]
ss=""
for oli in ol:
lt.append(oli.stripped_strings)
for i in lt:
for j in i:
ss+=" "
ss+=j
print(ss)
ul=download_soup.find_all('ul')
soup1 = BeautifulSoup(str(ul), 'lxml')
aa=soup1.find_all('li')
import bs4
sentences=''
for i in aa:
for j in i.descendants:
if j.string and type(j)!=bs4.element.Tag:
print(j)
sentences+=j.string.strip()
s='意思:'+ss+'\n'+"短语:"+sentences
#定义txt存储路径。
picpath='./newws2/'#这里我用的是本程序路径,也可改为c盘或d盘等路径。
def txt(name, text): # 定义函数名
if not os.path.exists(picpath): # 路径不存在时创建一个
os.makedirs(picpath)
savepath = picpath + name + '.txt'
file = open(savepath, 'a', encoding='utf-8')#因为一个网页里有多个标签p,所以用'a'添加模式
file.write(text)
# print(text)
file.close
txt(target,s)
输入样例:book
结果: