爬取英语六级高频词


任务

将网站中所有英语六级高频词以及翻译获取,然后进行存储
在这里插入图片描述


一、指定url

网站中单词被分开存放在1-7页中
第1页的url:http://www.oh100.com/kaoshi/cet6/cihui/249585.html
第2页的url:http://www.oh100.com/kaoshi/cet6/cihui/249585_2.html
第3页的url:
http://www.oh100.com/kaoshi/cet6/cihui/249585_3.html
从中可发现去除第1页外第i页的url为
http://www.oh100.com/kaoshi/cet6/cihui/249585_i.html

for i in range(1,8):#爬取1-7页
    #获取每一页的url
    url=f'http://www.oh100.com/kaoshi/cet6/cihui/249585_{str(i)}.html'
    if(i==1):
        url='http://www.oh100.com/kaoshi/cet6/cihui/249585.html'

二、发起请求并获取响应数据

def getHTML(url):
    r=requests.get(url)
    r.encoding=r.apparent_encoding
    return r.text

三、对响应数据进行数据解析

在这里插入图片描述   看到所有的单词都存在<div class=“content”>下的p标签中,可以用xpath获取数据。
在这里插入图片描述

  本路径下的p标签不都是单词,需要把不要的信息过滤。这里用try、except语句,在split对字符串中内容切片时切到非单词内容会报错并进入except中continue

def fx(text):
    tree=etree.HTML(text)
    p_list=[]#存储p标签
    p_list=tree.xpath('//div[@class="content"]/p')#匹配
    p_list.pop(0)
    p_list.pop(1)#前两个空格不要
    for p in p_list: 
        try:#保证取到的数据是单词和单词对应翻译
            mean.append(p.xpath('./text()')[0][2:].split('/')[2])#这里split('/')[2]会超出list长度报错退出,所以try中两条语句顺序不能调换,不然word长度和mean不同造成错位
            word.append(p.xpath('./text()')[0][2:].split('/')[0])            
            #print(word[-1:],mean[-1:])
        except:
            continue

四、持久化存储

f=open('./cet6word.txt','a',encoding='utf-8')
for i in range(1,len(word)):
    f.write(word[i]+' '+mean[i]+'\n')
f.close()

总结

本案例为xpath对静态页面的解析

代码如下(示例):

import requests
from lxml import etree
def getHTML(url):
    r=requests.get(url)
    r.encoding=r.apparent_encoding
    return r.text
def fx(text):
    tree=etree.HTML(text)
    p_list=[]
    p_list=tree.xpath('//div[@class="content"]/p')
    p_list.pop(0)
    p_list.pop(1)
    for p in p_list: 
        try:#保证取到的数据是单词和单词对应翻译
            mean.append(p.xpath('./text()')[0][2:].split('/')[2])
            word.append(p.xpath('./text()')[0][2:].split('/')[0])            
            #print(word[-1:],mean[-1:])
        except:
            continue
word=[]#存储单词
mean=[]#存储翻译
for i in range(1,8):#爬取1-7页
    #获取每一页的url
    url=f'http://www.oh100.com/kaoshi/cet6/cihui/249585_{str(i)}.html'
    if(i==1):
        url='http://www.oh100.com/kaoshi/cet6/cihui/249585.html'
    #发起请求
    text=getHTML(url)
    #数据分析
    fx(text)
    print('第%d页爬取完成\n'%i) 
#存储    
f=open('./cet6word.txt','a',encoding='utf-8')
for i in range(1,len(word)):
    f.write(word[i]+' '+mean[i]+'\n')
f.close()

部分结果:
在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值