任务描述
本关任务:前一关我们已经用requests获得了湖大首页的网页文件,这一关在此基础上对网页进行解析,获取首页新闻的标题和链接并分别保存到两个列表中,最后将两个列表的内容保存到文本文件中。
文本文件的格式如图所示:
相关知识
为了完成本关任务,你需要掌握:1.网页解析,2.同时遍历多个列表,3.文本文件操作
网页解析
网页解析的目标是从网页中获取自己需要的信息 导入库:from bs4 import BeautifulSoup 1.用BeautifulSoup将网页解析成标签树 soup = BeautifulSoup(html,html.parser') 2.用相关解析方法获取所需信息sopup find_all(): soup.find_all('a',{ 'class': 'item'}) #获得所有class属性值为item的a标签的列表 find(): soup.find('a') #获得第一条a标签 get(): a_tag.get('class') #获取标签a_tag的class属性值
同时遍历多个列表
例如:有两个列表list1,list2,用zip函数可以同步遍历两个列表: for i,j in zip(list1,list2) ...
文本文件操作
1.读文本文件实例
# coding=utf-8
with open('D:\test.txt','r') as f:
txt=f.read()
上述代码可以将D盘中的test.txt中的内容读到字符串txt中。
2.读文本文件实例
# coding=utf-8
txt='''Londoners are under starter's orders as the city gets ready for the Olympic Games, which will begin one year today.
'''
with open('D:\test.txt','w') as f:
f.write(txt)
上述代码可以将txt中的内容写入D盘下的test.txt文件。
编程要求
根据提示,在右侧编辑器补充代码,获取首页新闻的标题和链接并保存到文本文件。
测试说明
平台会对你编写的代码进行测试,比对你输出的结果与实际正确的结果,只有所有结果全部正确才算完成本关任务。
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 16:36:53 2020
@author: Administrator
"""
import requests
import bs4
from bs4 import BeautifulSoup
url="http://www.hnu.edu.cn/"
headers={
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
}
filename='hnu.txt'
def gethtml(url):
response=requests.get(url=url,headers=headers)
response.encoding='utf-8'
return response.text
def gettitle(html):
# 请按下面的注释提示添加代码,完成相应功能
###### Begin ######
# 1.解析网页,获取湖大首页上的新闻标题和链接,分别放入titles和hrefs列表
titles=[]
hrefs=[]
soup=BeautifulSoup(html,'html.parser')
res = soup.find("div", class_="hdxw-right fr")
tag_a = res.find_all("a", target="_blank")
for a in tag_a:
title_s=a.get('title')
href_s=a.get('href')
titles.append(title_s)
hrefs.append(href_s)
####### End #######
return titles,hrefs
def saveinfo(titles,hrefs,filename):
# 请按下面的注释提示添加代码,完成相应功能
###### Begin ######
# 2.将titles和hrefs列表中的内容保存到文件文件
for i,j in zip(titles,hrefs):
with open('hnu.txt','w') as f:
txt=f.write(i)
with open('hun.txt','w') as f:
txt=f.write(j)
####### End #######
html=gethtml(url)
titles,hrefs=gettitle(html)
saveinfo(titles,hrefs,filename)