第5关:爬取单页多个div标签的信息
任务描述
本关任务:改进上一关的代码。爬取湖南大学讲座网页的多个讲座信息,存储在二维列表 jzxx
中。
湖南大学讲座信息的网址为 https://www.hnu.edu.cn/xysh/xshd.htm
。
相关知识
1. find_all 函数
通过 BeautifulSoup
的 find_all(name,attr)
方法,可以找到符合条件的多个标签,将多个标签的内容返回为一个列表
lb=bg.find_all("div",class="xinwen-wen")
找到网页的所有 class
属性为 xinwen-wen
的 div
标签,存入列表 lb
。
2. 列表的操作
对于得到的多个标签的列表,使用 for
循环,可以依次访问每个标签,使用 find
函数找出其时间、标题和地点的文本,加入到列表,再加入二维列表 jzxx
中。
编程要求
根据提示,在右侧编辑器补充代码,爬取湖南大学讲座网页的多个讲座信息,存储在二维列表 jzxx
中
代码
import requests
from bs4 import BeautifulSoup
url = 'https://www.hnu.edu.cn/xysh/xshd.htm'
r = requests.get(url)
r.encoding = 'utf-8'
#代码开始
soup = BeautifulSoup(r.text, "html.parser")
xw = soup.find_all("div", class_="xinwen-wen")
jzxx=[]
for i in range(len(xw)):
jzxxx = []
jzsj = xw[i].find("div", class_="xinwen-sj-top").text.strip()
jzbt = xw[i].find("div", class_="xinwen-wen-bt").text.strip()
jzdd = xw[i].find("div", class_="xinwen-wen-zy").text.strip()
jzxxx.append(jzsj)
jzxxx.append(jzbt)
jzxxx.append(jzdd)
jzxx.append(jzxxx)
# print(jzxxx)
# print(jzxx)
f1=open("jzxx2.txt","w")
for xx in jzxx:
f1.write(",".join(xx)+"\n")
f1.close()
第6关:爬取多个网页的多个div标签的信息
任务描述
本关任务:修改上关的程序,爬取从第 80 页到 85 页中的讲座信息,存放在 jz.txt
文件中每行显示一个讲座信息,讲座时间、讲座标题和主讲人地点用逗号分隔。
如何将信息写入文件
首先以 w
方式打开文件,再通过文件对象的 write
方法将字符串写入文件。
代码
import requests
from bs4 import BeautifulSoup
f1 = open("jz.txt", "w", encoding="utf8")
# 代码开始
for i in range(80, 86):
respose = requests.get(f'https://www.hnu.edu.cn/xysh/xshd/{i}.htm')
respose.encoding = 'utf-8'
content = respose.text
soup = BeautifulSoup(content, 'html.parser')
all_div = soup.findAll('div', class_='xinwen-wen')
for div in all_div:
jzsj = div.find('div', class_='xinwen-sj-top').string.strip()
jzbt = div.find('div', attrs={'class', 'xinwen-wen-bt'}).string.strip()
jzdd = div.find('div', attrs={'class', 'xinwen-wen-zy'}).text.strip()
f1.write(jzsj + ',' + jzbt + ',' + jzdd + '\n')
# 代码结束
f1.close()