用Selenium抓取新浪天氣

2022-05-09 09:30:10 字數 3723 閱讀 8339

1)用selenium

系統環境: 

用虛擬環境實現

一、建立虛擬環境:

mkvirtualenv --python=/usr/bin/python python_2

二、啟用虛擬環境:

workon python_2

三、安裝selenium

pip install selenium

四、安裝firefox的selenium補丁檔案:

brew install geckodriver

五、在~/.bash_profile中增加一行:

export path=$path:/usr/local/cellar/geckodriver/0.22.0/bin

六、安裝beautifulsoup4、lxml、html5lib:

pip install beautifulsoup4

pip install lxml

pip install html5lib

python**:

#coding:utf-8

importsys

reload(sys)

sys.setdefaultencoding('utf8')

fromseleniumimportwebdriver

fromselenium.webdriver.common.keysimportkeys

importtime, datetime

frombs4importbeautifulsoup

driver = webdriver.firefox()

driver.get("")

assertu""indriver.title

elem = driver.find_element_by_id("hd_sh_input")

elem.clear()

elem.send_keys(u"長春")

time.sleep(2)

elem.send_keys(keys.return)

time.sleep(2)

handles = driver.window_handles

forhandleinhandles:  # 切換視窗

ifhandle != driver.current_window_handle:

# print 'switch to second window', handle

driver.close()  # 關閉第乙個視窗

driver.switch_to.window(handle)  # 切換到第二個視窗

html_const = driver.page_source

soup = beautifulsoup(html_const,'html.parser')

div_tag = soup.find_all("div", class_="blk_fc_c0_i")

foriindiv_tag:

fortagini.find_all(true):

iftag['class'][0] =='wt_fc_c0_i_date':

print"日期:", datetime.date.today().strftime('%y')+"-"+ tag.string

iftag['class'][0] =='wt_fc_c0_i_temp':

print"溫度:", tag.string

iftag['class'][0] =='wt_fc_c0_i_tip':

print"風力:", tag.string

iftag['class'][0] =='l':

print"pm5", tag.string

iftag['class'][0] =='r':

print"空氣質素:", tag.string

print"________________"

driver.close()

執行結果:

日期: 2018-09-30

溫度: 15°c / 7°c

風力: 北風 3~4級

pm5: 21

空氣質素: 優

日期: 2018-10-01

溫度: 15°c / 4°c

風力: 西北風 3~4級

pm5: 21

空氣質素: 優

日期: 2018-10-02

溫度: 19°c / 7°c

風力: 西風 小於3級

pm5: 40

空氣質素: 優

日期: 2018-10-03

溫度: 20°c / 8°c

風力: 西南風 小於3級

pm5: 58

空氣質素: 良

日期: 2018-10-04

溫度: 21°c / 9°c

風力: 西南風 小於3級

pm5: 57

空氣質素: 良

日期: 2018-10-05

溫度: 22°c / 9°c

風力: 西南風 小於3級

pm5: 40

空氣質素: 優

WebRequest使用 呼叫新浪天氣

待請求的位址 string url 建立 webrequest 物件,webrequest 是抽象類,定義了請求的規定,可以用於各種請求,例如 http,ftp 等等。httpwebrequest 是 webrequest 的派生類,專門用於 http 請求的方式通過 method 屬性設定 預設為...

PYTHON之抓取天氣資訊。

目錄簡介 獲取資料 輸出 郵箱傳送 爬蟲的基本思路 根據輸入的url進行爬取資料進行解析並獲取資料,最後儲存資料。爬取網頁資料案例 中國天氣網 獲取天氣資訊 如下 data list response requests.get url html doc response.text soup beau...

如何抓取新浪新聞資訊

如何將特殊標籤或節點的資料取出來。可以通過beautifulsoup中的select方法。例子frombs4importbeautifulsoup html sample this is link1 this is link2 soup beautifulsoup html sample,html....