任务
将网站中所有英语六级高频词以及翻译获取,然后进行存储
一、指定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()
部分结果: