BeautifulSoup爬取考研词汇

BeautifulSoup爬取考研词汇

1.网页源代码分析
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2.直接上代码

# -*- encoding:utf-8 -*-
import urllib.request          # 导入urllib库的request模块
from bs4 import BeautifulSoup  
import lxml                    #文档解析器
import os                      #os模块就是对操作系统进行操作
import numpy as np       #列表、字典、字符串等中计算元素重复的次数
 
urls=[]
titles=[]
#爬取所有新闻的url和标题,存储在urls和titles中,这里range(1)表示只爬取1页。   
for i in range(1):
    url='https://kaoyan.koolearn.com/20180428/1010928.html'
    res = urllib.request.urlopen(url)  #调用urlopen()从服务器获取网页响应(respone),其返回的响应是一个实例
    html = res.read().decode('utf-8')  #调用返回响应示例中的read(),可以读取html
    soup = BeautifulSoup(html, 'lxml')
    result = soup.find_all('div',attrs={'class':'xqy_core_text'})
download_soup = BeautifulSoup(str(result), 'lxml')
urls=[]
url_all = download_soup.find_all('a')
for a_url in url_all:
    a_title=a_url.get_text('target')
    if "考研英语5500词背诵" in a_title:
        urls.append(a_url.get('href'))
len(urls)
words=""
for i in urls:
    print(i)
    res = urllib.request.urlopen(i)  
    html = res.read().decode('utf-8') 
    soup = BeautifulSoup(html, 'lxml')
    result = soup.find_all('div',attrs={'class':"xqy_core_text"})
    download_soup = BeautifulSoup(str(result), 'lxml')
    lp = download_soup.find_all('p',attrs={'style':"white-space: normal;"})
    for p in lp:
        t = p.get_text()
        words+=t

#定义txt存储路径。
picpath='./newws3/'#这里我用的是本程序路径,也可改为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)
    file.close
txt("考研词汇5500",words)

3.结果
在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值