使用 BeautifulSoup 库抓取百度天气

本贴最后更新于 1372 天前,其中的信息可能已经事过景迁

最近研究了Python的BeautifulSoup库,用起来还挺好玩的
一、安装:使用pip命令在线安装;在cmd窗口中输入:pip install beautilfulsoup4

二、代码思路:
1.使用request获取相关网页的返回值,即HTML对象; 方法一
2.通过BeautifulSoup库对HTML页面元素进行解析,需要先分析要抓取的内容在哪里,再通过代码获取,存储在列表中;方法二
3.读取列表中内容,写入到csv文件中。方法三

from bs4 import BeautifulSoup
import requests
import csv
import xlwt

def GetContent(url):
    res=requests.get(url)
    # print(res.encoding)   # 查看res编码,如果不是utf-8,要在这里修改编码
    res.encoding='utf-8'
    return res.text

#将页面对象传入,通过beautifulSoup解析,获取对应的标签值,然后写入的excel中。
def GetWeath(html):
    final_data=[]
    soup=BeautifulSoup(html,"html.parser")     # 创建 BeautifulSoup对象
    # 1)查看源代码,找到最贴近需要爬取信息的外层的一个唯一标签;  2)然后使用findall找到对应每天的标签
    data=soup.find('ul',{"class":"t clearfix"})
    li=data.find_all("li")

    #遍历li标签,每一个li标签对应一天的天气状况
    for day in li:
        item=[]
        date=day.find("h1").string#zz找到日期,对应哪一天
        item.append(date)

        info=day.find_all("p")   #找到天气状况,并追加
        item.append(info[0].string)

#判断最高温度是否为空,为空则不写入,否则写入;追加最高和最低温度;
        if info[1].find("span") is None:
            temperature_highest=None
        else:
            temperature_highest=info[1].find("span").string
        temperature_lowest = info[1].find('i').string
        item.append(temperature_highest)
        item.append(temperature_lowest)

        #追加每次的数据
        final_data.append(item)
    # print(final_data)
    return final_data


# 将结果写入到csv文件中;注意编码格式;
def WriteCsv(title,data,filename):
    '''
    :param title: 第一行:标题;仅写入一次即可;
    :param data: 要写入的数据,列表形式,有多行多列;
    :param filename: 文件名;
    :return: 
    '''
    with open(filename,'w',newline='',encoding='utf_8_sig')as file:
        file_csv=csv.writer(file)
        file_csv.writerow(title)
        file_csv.writerows(data)


if __name__ == '__main__':
    url = 'http://www.weather.com.cn/weather/101120101.shtml'
    title=['日期','天气情况','最高气温','最低气温']  #csv文件的标题栏
    html=GetContent(url)
    data=GetWeath(html)
    WriteCsv(title,data,"result_weath.csv")

效果图:
image.png

回帖
请输入回帖内容 ...