Python天氣爬蟲

2021-10-07 06:30:39 字數 3300 閱讀 9156

)# 建立beautifulsoup物件

body = bs.body # 獲取body部分

data = body.find(

'div',)

# 找到id為7d的div

ul = data.find(

'ul'

)# 獲取ul部分

li = ul.find_all(

'li'

)# 獲取所有的li

for day in li:

# 對每個li標籤中的內容進行遍歷

temp =

date = day.find(

'h1'

).string # 找到日期

# 新增到temp中

inf = day.find_all(

'p')

# 找到li中的所有p標籤0]

.string,

)# 第乙個p標籤中的內容(天氣狀況)加到temp中

if inf[1]

.find(

'span')is

none

: temperature_highest =

none

# 天氣預報可能沒有當天的最高氣溫(到了傍晚,就是這樣),需要加個判斷語句,來輸出最低氣溫

else

: temperature_highest = inf[1]

.find(

'span'

).string # 找到最高溫

temperature_highest = temperature_highest.replace(

'℃','')

# 到了晚上**會變,最高溫度後面也有個℃

temperature_lowest = inf[1]

.find(

'i')

.string # 找到最低溫

temperature_lowest = temperature_lowest.replace(

'℃','')

# 最低溫度後面有個℃,去掉這個符號

# 將最高溫新增到temp中

#將最低溫新增到temp中

#將temp加到final中

return final

defwrite_data

(data, name)

: file_name = name

with

open

(file_name,

'a', errors=

'ignore'

, newline='')

as f:

f_csv = csv.writer(f)

f_csv.writerows(data)

if __name__ ==

'__main__'

: url =

''html = get_content(url)

result = get_data(html)

write_data(result,

'weather.csv'

)

python爬蟲之墨跡天氣

import requests from lxml.html import etree import json import time 匯入模組 class mojiweather def city name self 定義乙個輸入城市名稱的函式 cityname str input 輸入城市名稱 ...

python網頁爬蟲之天氣查詢

這是用python寫的天氣查詢 可用。這裡用的是和風天氣的介面 參考 我用的城市資料 將城市資料存放本地 jsons import pickle pickle file open city data.pkl wb pickle.dump jsons,pickle file pickle file.c...

Python簡單爬蟲(爬取天氣資訊)

初學python,學到python爬蟲時在網上找資料,發現找到的大部分都是前部分內容對運作方式介紹,然後就直接上 了,這樣對像我一樣的小白來說比較困難,的注釋較少,部分 塊沒有詳細說明運作方式和具體作用,所以寫此筆記方便別人和自己以後進行學習檢視。作業系統window python2.7.10 wi...