第一个Splinter脚本

# -*- coding: utf-8 -*-

from splinter.browser import Browser

import time



bs = Browser('chrome')

time.sleep(3)

# 最大化浏览器

bs.driver.maximize_window()

time.sleep(1)

bs.visit('https://www.baidu.com')

time.sleep(3)

if bs.is_element_present_by_xpath("//input[@id='kw']"):

    bs.find_by_xpath("//input[@id='kw']")[0].fill(u'珠海天气')

else:

    print '找不到 百度 输入框'

time.sleep(3)

if bs.is_element_present_by_xpath("//input[@id='su']"):

    bs.find_by_xpath("//input[@id='su']")[0].click()

else:

    print '找不到 百度一下 按钮'


if bs.is_element_present_by_text('珠海气象'):

    print '找到 珠海气象 '

else:

    print '找不到 珠海气象'


这里我们以百度搜索为例讲解splinter脚本。


1,首先是导入splinter包:from splinter.browser import Browser


2,实例化一个浏览器对象:bs = Browser('chrome')


splinter支持chrome,firefox浏览器,默认是firefox,如果不写浏览器驱动就以firefox启动的,比如bs = Browser()将会启动firefox,如果系统没有安装,则会报错。


3,浏览器打开一个网址:visit


bs.visit('https://www.baidu.com')

visit方法用于访问一个页面。


4,判断页面元素是否存在:is_element_present_by_xpath


这里我们判断是百度那个搜索框是否存在,这个搜索的id值是kw。想要知道页面上某个元素的属性和值,

可以在浏览器按F12,然后右击页面的元素,点击“检查”即可查看,如下图:

2.png

5,填写要搜索的内容:fill

fill方法是向页面填写内容

find_by_xpath("//input[@id='kw']")[0].fill(u'珠海天气')

这里是先通过find_by_xpath找到元素,再fill一个值“珠海天气”,注意一下[0],

这个是因为find_by_xpath返回值是一个列表,所以要用下标来取值。


6,点击百度一下按钮:click

click方法就是用来点击页面元素的

find_by_xpath("//input[@id='su']")[0].click()


7,判断页面某元素是否出现:is_element_present_by_text

这个是通过文本来判断,上面第4步is_element_present_by_xpath是通过 xpath来判断。其他都可以看哪个方便。


该文章对你有帮助吗,求分享转发: 分享到QQ空间 分享给QQ好友

 

 

粤ICP备19116230号
友情链接: 码农藏书阁 天天链