selenium 操控浏览器

如果是火狐浏览器那就最好啦,因为不用下载额外控件
#-*-coding:utf-8 -*-
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import time
import os
import urllib,urllib2

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#不用下载额外的插件
driver = webdriver.Firefox()
driver.get('http://www.baidu.com')
assert u'百度' in driver.title



elem = driver.find_element_by_name("wd")
elem.send_keys(u"天空之城")
#elem.send_keys(Keys.RETURN)
time.sleep(5)
driver.close()


driver.quit()



如果是谷歌浏览器:

#需要下载chromedriver.exe
chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver


driver = webdriver.Chrome(chromedriver)
driver.get('http://www.baidu.com')
assert u'百度' in driver.title
elem = driver.find_element_by_name("wd")
elem.send_keys("haha")

#elem.send_keys(Keys.RETURN)


driver.close()
driver.quit()

chromedriver.exe下载


如果是PhantomJS(无UI浏览器):

下载、安装地址:http://phantomjs.org/download.html ,要下载一个phantomjs.exe,并设置好环境变量。

下面代码实现了,用PhantomJS解析JS,获取验证码URL,并下载验证码的功能:

# #coding:utf-8  
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtWebKit import*
from PyQt4 import QtCore, QtGui
from PyQt4 import uic
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
import time,datetime
from bs4 import BeautifulSoup
import urllib,urllib2,httplib,cookielib
import os,sqlite3,re
import uuid
import hashlib
import sys
import ctypes
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

reload(sys)
sys.setdefaultencoding('utf-8')

driver = webdriver.PhantomJS()

#获取验证码	
myindex = 0
cnt_num = 4
title = u'泰润'
login_url = "http://52.74.222.142:8212/sscne12313f/user/login.html.auth"
while True:
    driver.get(login_url)
    #坐等加载好
    time.sleep(5)
    try:
        img_src = driver.find_element_by_id('img').find_element_by_tag_name('img').get_attribute('src')
        print img_src
        img_file = urllib2.urlopen(img_src)
        file = './checkcodejpg/checkcode'+str(myindex)+'.jpg'
        print myindex,file
        jpg = open(file,'wb')
        jpg.write(img_file.read())
        jpg.close()
        myindex += 1
    except Exception,e:
        print e
        



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值