首页 > 其他 > 详细

用Selenium抓取新浪天气

时间:2018-09-30 19:45:34      阅读:250      评论:0      收藏:0      [点我收藏+]

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抓取新浪天气

原文:https://www.cnblogs.com/herosoft/p/9733002.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!