使用Python和BS4刮取天气预测数据

使用Python和BS4刮取天气预测数据

这篇文章围绕着使用python和bs4库刮取天气预报d数据。让我们来看看脚本中使用的组件 –

BeautifulSoup – 它是一个强大的Python库,用于从HTML/XML文件中提取数据。它为解析过的页面创建一个解析树,可以用来从HTML/XML文件中提取数据。

Requests – 它是一个Python HTTP库。它使HTTP请求更加简单。我们只需要添加URL作为参数,然后get()就可以从中获得所有的信息。

我们将从https://weather.com/en-IN/weather/tenday/l/INKA0344:1:IN 中搜刮数据。第1步 – 运行以下命令,从URL中获取存储的内容到响应对象(文件)。

import requests
# to get data from website
file = requests.get("https://weather.com/en-IN/weather/tenday/l/INKA0344:1:IN")
Python

第2步 –解析HTML内容。

# import Beautifulsoup for scraping the data
from bs4 import BeautifulSoup
soup = BeautifulSoup(file.content, "html.parser")
Python

第3步 –从天气网站搜刮数据,运行以下代码。

# create empty list
list =[]
all = soup.find("div", {"class":"locations-title ten-day-page-title"}).find("h1").text
  
# find all table with class-"twc-table"
content = soup.find_all("table", {"class":"twc-table"})
for items in content:
    for i in range(len(items.find_all("tr"))-1):
                # create empty dictionary
        dict = {}
        try:  
                        # assign value to given key
 
            dict["day"]= items.find_all("span", {"class":"date-time"})[i].text
            dict["date"]= items.find_all("span", {"class":"day-detail"})[i].text           
            dict["desc"]= items.find_all("td", {"class":"description"})[i].text
            dict["temp"]= items.find_all("td", {"class":"temp"})[i].text
            dict["precip"]= items.find_all("td", {"class":"precip"})[i].text
            dict["wind"]= items.find_all("td", {"class":"wind"})[i].text
            dict["humidity"]= items.find_all("td", {"class":"humidity"})[i].text
        except: 
                     # assign None values if no items are there with specified class
 
            dict["day"]="None"
            dict["date"]="None"
            dict["desc"]="None"
            dict["temp"]="None"
            dict["precip"]="None"
            dict["wind"]="None"
            dict["humidity"]="None"
 
        # append dictionary values to the list
        list.append(dict)
Python

find_all:它用于拾取作为参数传入的标签的所有HTML元素及其后代。
find:它将搜索所传递的标签的元素。
list.append(dict):这将把所有的数据追加到list类型的列表中。

第4步 – 将列表文件转换成CSV文件,以查看有组织的天气预报数据。使用以下代码将列表转换为CSV文件,并将其存储到output.csv文件中。

import pandas as pd
convert = pd.DataFrame(list)
convert.to_csv("output.csv")
Python

语法:

pandas.DataFrame(data=None, index: Optional[Collection] = None, columns: Optional[Collection] = None, dtype: Union[str, numpy.dtype, ExtensionDtype, None] = None, copy: bool = False) 
Python

**参数: **

data: Dict可以包含系列、数组、常数或类似列表的对象。

index : 它用于结果框架。如果输入数据中没有索引信息,也没有提供索引,则默认为RangeIndex。columns:列的标签,用于结果框架。如果没有提供列标签,将默认为RangeIndex(0,1,2,…,n)。

dtype: 它用于设置默认值。

copy: 它从输入的数据中复制,默认值为false。

# read csv file using pandas
a = pd.read_csv("output.csv")
print(a)
Python

输出 :

使用Python和BS4刮取天气预测数据

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册