Selenium对浏览器的各种操作

简介:
第一步就是安装 Selenium这个模块,当然,前提是你的python已经安装好了
  直接在dos窗口输入
  pip install selenium完成一键安装
  然后就可以新建一个py文件,在里面输入
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# go to the  google home page
driver.get("http://www.google.com")
# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")
# type in the search
inputElement.send_keys("cheese!")
# submit the form (although google automatically searches now without submitting)
inputElement.submit()
# the page is ajaxy so the title is originally this:
print driver.title
try:
# we have to wait for the page to refresh, the last thing that seems to be updated is the title
WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))
# You should see "cheese! - Google Search"
print driver.title
finally:
driver.quit()
  这样就打开google进行查找cheese!后打印标题并关闭浏览器
  下面介绍各种获取浏览器内的各种元素的方法
By ID
<divid="coolestWidgetEvah">...</div>
element=driver.find_element_by_id("coolestWidgetEvah")
By Class Name
<divclass="cheese"><span>Cheddar</span></div><divclass="cheese"><span>Gouda</span></div>
cheeses=driver.find_elements_by_class_name("cheese")
By Tag Name
<iframesrc="..."></iframe>
frame=driver.find_element_by_tag_name("iframe")
By Name
<inputname="cheese"type="text"/>
cheese=driver.find_element_by_name("cheese")
By Link Text
<a href="http://www.google.com/search?q=cheese">cheese</a>>
cheese=driver.find_element_by_link_text("cheese")
By Partial Link Text
<a href="http://www.google.com/search?q=cheese">search for cheese</a>
cheese=driver.find_element_by_partial_link_text("cheese")
By CSS
<divid="food"><spanclass="dairy">milk</span><spanclass="dairy aged">cheese</span></div>
cheese=driver.find_element_by_css_selector("#food span.dairy.aged")
By XPATH
<inputtype="text"name="example"/><INPUTtype="text"name="other"/>
inputs=driver.find_elements_by_xpath("//input")
  (相关的XPATH教程具体可以参考W3C的教程进行学习)
  Using JavaScript
  这么这是两个例子,例子一需要提前加载jqury的支持
  element=driver.execute_script("return $('.cheese')[0]")
  labels=driver.find_elements_by_tag_name("label")inputs=driver.execute_script("var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){"+"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;",labels)
  User Input - Filling In Forms
  select=driver.find_element_by_tag_name("select")allOptions=select.find_elements_by_tag_name("option")foroptioninallOptions:print"Value is: "+option.get_attribute("value")option.click()
  有些选择提取的元素是需要进行筛选的如
  # available since 2.12fromselenium.webdriver.support.uiimportSelectselect=Select(driver.find_element_by_tag_name("select"))select.deselect_all()select.select_by_visible_text("Edam")
  那么这些form进行如何提交呢?
  driver.find_element_by_id("submit").click()
  element.submit()
  Moving Between Windows and Frames
  <a href="somewhere.html"target="windowName">Click here to open a new window</a>
  driver.switch_to_window("windowName")
  driver.switch_to_frame("frameName")
  driver.switch_to_frame("frameName.0.child")
  切换一些弹出来的比如登录框等
  Popup Dialogs
  这类的有alerts, confirms, and prompts等
  alert=driver.switch_to_alert()
  返回的是一个弹窗的窗体对象
  Cookies
  # Go to the correct domaindriver.get("http://www.example.com")# Now set the cookie. Here's one for the entire domain# the cookie name here is 'key' and its value is 'value'driver.add_cookie({'name':'key','value':'value','path':'/'})# additional keys that can be passed in are:# 'domain' -> String,# 'secure' -> Boolean,# 'expiry' -> Milliseconds since the Epoch it should expire.# And now output all the available cookies for the current URLforcookieindriver.get_cookies():print"%s -> %s"%(cookie['name'],cookie['value'])# You can delete cookies in 2 ways# By namedriver.delete_cookie("CookieName")# Or all of themdriver.delete_all_cookies()
  Changing the User Agent
  profile=webdriver.FirefoxProfile()profile.set_preference("general.useragent.override","some UA string")driver=webdriver.Firefox(profile)
  Drag And Drop
fromselenium.webdriver.common.action_chainsimportActionChainselement=driver.find_element_by_name("source")target=driver.find_element_by_name("target")ActionChains(driver).drag_and_drop(element,target).perform()
  具体的详细用法可以参考官方文档:http://docs.seleniumhq.org/docs/03_webdriver.jsp


最新内容请见作者的GitHub页:http://qaseven.github.io/
相关文章
|
1月前
|
Web App开发 Java 测试技术
多任务一次搞定!selenium自动化复用浏览器技巧大揭秘
多任务一次搞定!selenium自动化复用浏览器技巧大揭秘
42 1
|
1月前
|
Web App开发 Java 测试技术
《手把手教你》系列基础篇之(四)-java+ selenium自动化测试- 启动三大浏览器(下)基于Maven(详细教程)
【2月更文挑战第13天】《手把手教你》系列基础篇之(四)-java+ selenium自动化测试- 启动三大浏览器(下)基于Maven(详细教程) 上一篇文章,宏哥已经在搭建的java项目环境中实践了,今天就在基于maven项目的环境中给小伙伴们 或者童鞋们演示一下。
66 1
|
1月前
|
Web App开发 Java 测试技术
《手把手教你》系列基础篇之(三)-java+ selenium自动化测试- 启动三大浏览器(上)(详细教程)
【2月更文挑战第12天】《手把手教你》系列基础篇之(三)-java+ selenium自动化测试- 启动三大浏览器(上)(详细教程) 前边宏哥已经将环境搭建好了,今天就在Java项目搭建环境中简单地实践一下: 启动三大浏览器。按市场份额来说,全球前三大浏览器是:IE.Firefox.Chrome。因此宏哥这里主要介绍一下如何启动这三大浏览器即可,其他浏览器类似的方法,照猫画虎就可以了。
44 1
|
1天前
|
数据采集 前端开发 测试技术
《手把手教你》系列技巧篇(三十一)-java+ selenium自动化测试- Actions的相关操作-番外篇(详解教程)
【4月更文挑战第23天】本文介绍了网页中的滑动验证码的实现原理和自动化测试方法。作者首先提到了网站的反爬虫机制,并表示在本地创建一个没有该机制的网页,然后使用谷歌浏览器进行验证。接着,文章详细讲解了如何使用WebElement的click()方法以及Action类提供的API来模拟鼠标的各种操作,如右击、双击、悬停和拖动。
6 2
|
2天前
|
Web App开发 数据采集 Java
《手把手教你》系列技巧篇(三十)-java+ selenium自动化测试- Actions的相关操作下篇(详解教程)
【4月更文挑战第22天】本文介绍了在测试过程中可能会用到的两个功能:Actions类中的拖拽操作和划取字段操作。拖拽操作包括基本讲解、项目实战、代码设计和参考代码,涉及到鼠标按住元素并将其拖动到另一个元素上或指定位置。划取字段操作则介绍了如何在一段文字中随机选取一部分,包括项目实战、代码设计和参考代码。此外,文章还提到了滑动验证的实现,并提供了相关的代码示例。
28 2
|
9天前
|
Java 测试技术 定位技术
《手把手教你》系列技巧篇(二十三)-java+ selenium自动化测试-webdriver处理浏览器多窗口切换下卷(详细教程)
【4月更文挑战第15天】本文介绍了如何使用Selenium进行浏览器窗口切换以操作不同页面元素。首先,获取浏览器窗口句柄有两种方法:获取所有窗口句柄的集合和获取当前窗口句柄。然后,通过`switchTo().window()`方法切换到目标窗口句柄。在项目实战部分,给出了一个示例,展示了在百度首页、新闻页面和地图页面之间切换并输入文字的操作。最后,文章还探讨了在某些情况下可能出现的问题,并提供了一个简单的本地HTML页面示例来演示窗口切换的正确操作。
37 0
|
11天前
|
JavaScript 前端开发 安全
JavaScript DOM 操作:解释一下浏览器的同源策略。
**同源策略**是浏览器安全基石,它阻止脚本跨不同协议、域名或端口访问资源,防止恶意行为。例如,HTTP页面无法直接用JS获取HTTPS页面内容。**CORS**允许跨域请求,但需服务器配合设置,通过`document.domain`属性可配置,但仍受限于服务器配置。
14 4
|
18天前
【超实用】Angular如何修改当前页面网页浏览器url后面?param1=xxx&param2=xxx参数(多用于通过浏览器地址参数保存用户当前操作状态的需求),实现监听url路由切换、状态变化。
【超实用】Angular如何修改当前页面网页浏览器url后面?param1=xxx&param2=xxx参数(多用于通过浏览器地址参数保存用户当前操作状态的需求),实现监听url路由切换、状态变化。
|
18天前
|
JavaScript
【归总】原生js操作浏览器hash、url参数参数获取/修改方法合集
【归总】原生js操作浏览器hash、url参数参数获取/修改方法合集
|
1月前
|
Web App开发 数据可视化 测试技术
Selenium Headless模式:无头浏览器的使用与优势
Selenium Headless模式是无界面的自动化测试方式,适用于Chrome和Firefox等浏览器,提供更快的速度、更高的隐秘性和资源节省。在Python中启用该模式,需导入Options并设置相关参数。示例代码展示了如何在无头模式下访问网站、执行点击和输入操作。这种模式提升了测试效率和稳定性,尤其适合大规模测试和CI环境。
37 1