浏览器相关的模块

webbrowser

webbrowser是一个python自带的模块,该模块一共6个方法:

["Error", "open", "open_new", "open_new_tab", "get", "register"]

使用方法:

1、webbrowser.open("www.baidu.com")  会使用系统默认的浏览器打开网页,比如IE

2、webbrowser.get('firefox').open('www.baidu.com', new=1,autoraise=True)  指定只用firefox浏览器打开网页

当然也可以使用rgister注册一个浏览器,比如360浏览器子类的:

import webbrowser 
360Path = r'你的浏览器目录'
webbrowser.register('360', None, webbrowser.BackgroundBrowser(360Path)) 
webbrowser.get('360').open('www.baidu.com',new=1,autoraise=True)

 官方文档:https://docs.python.org/3.5/library/webbrowser.html

 

selenium - Web Browser Automation

这个三方库太强大了,可以对浏览器做各种自动化的操作,自动化测试,当然用它来写爬虫当然是更加强悍。

官方文档:http://selenium-python.readthedocs.io/index.html

selenium有很强大的页面交互能力

比如点击,输入等等。前提就是要找到页面中的元素。WebDriver提供了各种方法来寻找元素。例如下面有一个表单输入框。

例如:

<input type="text" name="passwd" id="passwd-id" />

我们可以这样获取它:

element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_elements_by_tag_name("input")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
是不是感觉跟js的DOM操作非常类似
 
简单的示例: 实现一个web页面的自动登录,然后自动跳转到某个页面
import time

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

url = "https://vwapbjsvra01.ap.vwg/SAAS/t/VGC/auth/login?dest=" \
      "https://vwapbjsvra01.ap.vwg/SAAS/auth/oauth2/authorize?response_type%3Dcode%26client_id%" \
      "3Dcsp-admin-HlQkQLoJZQ%26state%3DD8D82B21ED9D4EB5306CD025C054C186%26redirect_uri%3D" \
      "https://vwapbjsvra01.ap.vwg/vcac/org/vgc/#com.vmware.csp.component.ipam.service.network.profiles"


wd = webdriver.Firefox(firefox_profile="C:\\Users\\gck1d6o\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\7gny7wzm.default",
                       firefox_binary="C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")
wd.get(url)
wd.maximize_window()

try:
    username = WebDriverWait(wd, timeout=5).until(EC.presence_of_element_located((By.ID, "username")), message="timeout")
    username.send_keys("admin")
    password = WebDriverWait(wd, timeout=5).until(EC.presence_of_element_located((By.ID, "password")), message="timeout")
    password.send_keys("passwd")
    wd.find_element_by_id("loginFormSubmit").click()
    time.sleep(5)
    wd.find_element_by_id("cafe.work.items").click()
except NoSuchElementException as e:
    print(e.msg)

 

 

posted @ 2017-05-04 14:29  Vincen_shen  阅读(351)  评论(0)    收藏  举报