1. 程式人生 > >用Selenium抓取新浪天氣

用Selenium抓取新浪天氣

空氣 rom cell parse beautiful 西北風 port $path 系統環境

1)用Selenium抓取新浪天氣

系統環境:

操作系統:macOS 10.13.6 python :2.7.10

用虛擬環境實現

一、創建虛擬環境:

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

import sys

reload(sys)

sys.setdefaultencoding(‘utf8‘)

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

import time, datetime

from bs4 import

BeautifulSoup

driver = webdriver.Firefox()

driver.get("http://weather.sina.com.cn")

assert u"新浪" in driver.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

for handle in

handles: # 切換窗口

if handle != 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")

for i in div_tag:

for tag in i.find_all(True):

if tag[‘class‘][0] == ‘wt_fc_c0_i_date‘:

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

if tag[‘class‘][0] == ‘wt_fc_c0_i_temp‘:

print "溫度:", tag.string

if tag[‘class‘][0] == ‘wt_fc_c0_i_tip‘:

print "風力:", tag.string

if tag[‘class‘][0] == ‘l‘ :

print "PM5", tag.string

if tag[‘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

空氣質量: 優

________________

用Selenium抓取新浪天氣