zoukankan      html  css  js  c++  java
  • Python:使用 BeautifulSoup 库抓取百度天气

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

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

    ```python
    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")

    ```
    效果图:

  • 相关阅读:
    循环的中断
    创建.NET应用程序所经历的步骤
    完整的开发一个ContentProvider步骤
    Perl 基于OOP的数据库链接(增删改查)
    Perl 基于OOP的数据库链接(优化)
    Perl 基于OOP的数据库链接
    Perl oop链接数据库
    Perl oop研究
    PythonStudy——内存管理机制 Memory management mechanism
    博客园美化——Design by Venti
  • 原文地址:https://www.cnblogs.com/test123/p/11382040.html
Copyright © 2011-2022 走看看