网络爬虫2-bs4

#头歌#

第三关

任务描述

本关任务:根据上个步骤中爬取的表格内容,将城市名称和人口数存放在列表 lb 中,按人口数降序排列后输出。

代码

import requests

from bs4 import BeautifulSoup

url = "https://tjj.hunan.gov.cn/hntj/tjfx/tjgb/pcgbv/202105/t20210519_19079329.html"

r = requests.get(url)

r.encoding = 'utf-8'

soup = BeautifulSoup(r.text,"html.parser")

bg = soup.find('table')

#代码开始

lb = bg.find_all("tr")

citys = {}

for i in range(3,len(lb)):

    #print(lb[i])

    datas = lb[i].find_all("td")

    #print(datas)

    str1 = ""

    for i in range(0,2):

        data = datas[i].find("p").text

        str1 += data + ' '

    result = str1.split()

    citys[result[0]] = int(result[1])

# 按人口数量对城市进行排序

sorted_cities = sorted(citys.items(), key=lambda x: x[1], reverse=True)

# 输出排序后的结果

for city, population in sorted_cities:

    print(f"{city} {population}")

第四关

任务描述

本关任务:编写一个爬取湖南大学讲座信息网页的程序。

湖南大学讲座信息的网址为 https://www.hnu.edu.cn/xysh/xshd.htm

编写程序,爬取该页第一个讲座的时间、标题、主讲人和地点信息,存储在字符串 jzsjjzbtjzdd 中,如下所示:

代码

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("div", class_="xinwen-wen")

jzsj = xw.find("div", class_="xinwen-sj-top").text.strip()

# print(jzsj)

jzbt=xw.find("div", class_="xinwen-wen-bt").text.strip()

# print(jzbt)

jzdd=xw.find("div", class_="xinwen-wen-zy").text.strip()

# print(jzdd)

#代码结束

f1=open("jzxx.txt","w")

f1.write(jzsj+"\n")

f1.write(jzbt+"\n")

f1.write(jzdd+"\n")

f1.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值