-利用BeautifulSoup库爬取墨迹天气网
时间: 2024-01-03 19:04:23 浏览: 33
使用BeautifulSoup库可以很方便地爬取墨迹天气网的信息。首先,你需要安装BeautifulSoup库,可以使用pip install BeautifulSoup4命令进行安装。安装完成后,你可以根据墨迹天气的网址,使用urlopen方法打开网页并获取网页内容。然后,使用BeautifulSoup库的解析器对网页内容进行解析。你可以使用find方法找到对应的元素,并提取需要的信息。比如,你可以使用find方法找到空气质量的元素,并使用string属性获取其文字内容。同样的,你可以找到当前温度和天气的元素,并提取相应的信息。下面是一个使用BeautifulSoup库爬取墨迹天气网信息的示例代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = urlopen('https://tianqi.moji.com/weather/china/beijing/haidian-district')
soup = BeautifulSoup(url, 'html.parser')
alert = soup.find('div', class_="wea_alert clearfix").em
print("空气质量:" + alert.string)
weather = soup.find('div', class_="wea_weather clearfix")
print("当前温度:" + weather.em.string + "℃")
print("天气:" + weather.b.string)