利用beautiful soup爬取歷史天氣資料

2021-10-07 22:12:25 字數 3513 閱讀 8984

利用beautiful soup爬取歷史天氣資料

本文將會涉及requests.get()返回結果為404時,採用模擬瀏覽器訪問的模式。以及當遇到幾個相同的標籤時的處理辦法。由於本人還是個小白,故可能有不好的地方

參考了:以及

文章爬取的**為

**如下

//

"""目標:

爬取2023年香洲的天氣資料,包括最高氣溫,最低氣溫,天氣,風向

並將資料儲存到xiangzhou.txt中

在bs4中若遇上相同的標籤,則使用find_next()

該程式還加上當遇到反爬蟲時利用模擬瀏覽器訪問的方式進行爬取

"""import requests

from bs4 import beautifulsoup

import time

"""定義乙個抓取頁面內容的函式"

""def get_html

(url)

:try

: #使用該句模擬瀏覽器訪問

headers =

r = requests.

get(url, headers=headers, timeout=30)

r.raise_for_status()

r.encoding =

'utf-8'

return r.text

except:

return

"error"

def get_content

(url,tianshu)

: comments =

html =

get_html

(url)

#做湯""

"lxml html解析器"

"" soup =

beautifulsoup

(html,

"lxml"

) # 按照之前的分析,我們找到所有具有『 j_thread_list clearfix』屬性的li標籤。返回乙個列表型別。

uls = soup.

find

('ul'

, attrs=

)for i in

range

(tianshu)

: uls = uls.

find_next

('li'

) # 初始化乙個字典來儲存文章資訊

comment =

# comment =

# 開始篩選資訊,並儲存到字典中

try: comment[

'riqi'

]= uls.

find

('div'

, attrs=

).text.

strip()

comment[

'maxt'

]= uls.

find

('div'

, attrs=

).text.

strip()

mint = uls.

find

('div'

, attrs=).

find_next

('div'

) comment[

'mint'

]= mint.text.

strip()

tianqi = mint.

find_next

('div'

) comment[

'tianqi'

]= tianqi.text.

strip()

fengxiang = tianqi.

find_next

('div'

) comment[

'fengxiang'

]= fengxiang.text.

strip()

comments.

(comment)

except:

print

('出了點小問題'

)return comments

def out2file

(dict)

:"""

定義乙個函式將爬取到的檔案寫入本地,儲存到當前目錄的abc.txt檔案中

"""with

open

('xiangzhou.txt'

,'a+'

)as f:

for comment in dict:

f.write

(comment[

'riqi']+

'\t'

+comment[

'maxt']+

'\t'

+comment[

'mint']+

'\t'

+comment[

'tianqi']+

'\t'

+comment[

'fengxiang'])

f.write

('\n'

)print

("當前頁面爬取完成"

)def main

(base_url,yue)

: url_list =

deep =

['01'

,'02'

,'03'

,'04'

,'05'

,'06'

,'07'

,'08'

,'09'

,'10'

,'11'

,'12'

]for i in

range(12

):url_list.

(base_url + deep[i]

+'.html'

)print()

#迴圈寫入所有的資料

for i in

range

(len

(url_list)):

content =

get_content

(url_list[i]

,yue[i]

)out2file

(content)

print

("所有的資訊都已經儲存完畢"

)if __name__ ==

"__main__"

: base_url =

"xiangzhouqu/2019"

# 設定需要爬取的頁碼數量

#deep =

3 yue =[31

,28,31

,30,31

,30,31

,31,30

,31,30

,31]main

(base_url,yue)

結果如下圖所示

利用BeautifulSoup網頁抓去資料

import requests from bs4 import beautifulsoup r requests.get soup beautifulsoup r.text,html5lib body soup.find body data soup.find id cpdata print typ...

BeautifulSoup常用方法

1.初始化 2.查詢指定標籤 eg 要找到符合的所有標籤 p.findall div 反覆利用標籤特徵可以找到最終需要的標籤 3.直接加標籤名可以找到所有子標籤 eg 找到所有標籤 p.td 4.直接以字典形式,可以訪問標籤內對應屬性的值 eg 要找到 中href 的值 www.csdn.net p...

BeautifulSoup學習筆記

prettify 將html 格式化 get text 獲得所有文字內容 contens 返回所有子節點 children 返回子節點生成器 descendants 返回所有子孫節點的生成器 strings 返回包含的多個字串的生成器 stripped strings 返回包含的多個字串 去除多餘空...