您的位置:首页 > 其它

ubuntu系统上splinter使用笔记

2015-08-06 19:45 369 查看
splinter可以实现浏览器自动化操作,并且通过设置参数可以使用headless模式工作。splinter文档点这里

一、 安装

$ sudo pip install splinter pytest-splinter


二、示例代码

1. 有图形界面:

#!/usr/bin/env python

from splinter.browser import Browser
import time

url= "http://www.tvbts.com"
with Browser() as browser:
  browser.visit(url)
  # login
  browser.fill('username', 'zhuliting')
  browser.fill('password', 'xxxxxx')
  browser.find_by_xpath('//button[@type="submit"]').first.click()

  #browser.click_link_by_href('/milist.html')
  browser.find_by_xpath('//*[@id="mn_N4233"]/a').first.click()
  print browser.url

  l = len(browser.find_by_xpath('//div[@class="pg"]/a'))
  for i in range(l):
    browser.find_by_xpath('//div[@class="pg"]/a')[i].click()
    print browser.url
    time.sleep(2)

    # save screenshot
    # file_name = "/home/zhuliting/png/" + str(i) + ".png"
    # browser.screenshot(file_name)

    ll = len(browser.find_by_xpath('//*[@class="s xst"]'))
    for j in range(ll):
      browser.find_by_xpath('//*[@class="s xst"]')[j].click()
      time.sleep(3)
      if (len(browser.windows) > 1):
        browser.windows[1].close()


2. 创建Browser实例的时候,如果不传入参数,WebDriver默认为firefox, 程序运行时,会打开firefox浏览器;如果要实现headless mode, 可以传入"phantomjs". 代码如下:

#!/usr/bin/env python

from splinter.browser import Browser
import time

url= "http://www.tvbts.com"
with Browser('phantomjs') as browser:
  browser.visit(url)
  # login
  browser.fill('username', 'zhuliting')
  browser.fill('password', 'xxxxx')
  browser.find_by_xpath('//button[@type="submit"]').first.click()

  #browser.click_link_by_href('/milist.html')
  browser.find_by_xpath('//*[@id="mn_N4233"]/a').first.click()
  print browser.url

  l = len(browser.find_by_xpath('//div[@class="pg"]/a'))
  for i in range(l):
    browser.find_by_xpath('//div[@class="pg"]/a')[i].click()
    print browser.url

    # save screenshot
    file_name = "/home/zhuliting/png/" + str(i) + ".png"
    browser.screenshot(file_name)

    contents = browser.find_by_xpath('//*[@class="s xst"]')
    for content in contents:
      print content.value
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: