首页 > 其他分享 >selenium

selenium

时间:2023-07-11 17:23:15浏览次数:36  
标签:webdriver get selenium element import browser


Python Automation Scripts Examples Use Django And Selenium

Django is the most popular web framework in the python world. You can use it to create a website quickly and simply. Selenium is the most popular website automation testing framework, it can be used to implement website automation function testing in source code with coding language python, java, etc. This example will tell you how to set up and run Django and Selenium to make a development environment for website functional tests.

 

 

If you do not install Python Django and selenium modules, you need to install them first. You can run the command pip list in a terminal to verify the Python Django and selenium module installation. If the two modules do not exist in the list, follow the below steps to install them.

1. Use Pip To Install Django Python Module.

192:~ $ pip install django Collecting django Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB) 100% |████████████████████████████████| 7.3MB 200kB/s Requirement already satisfied: pytz in ./anaconda3/lib/python3.6/site-packages (from django) (2018.4) Installing collected packages: django Successfully installed django-2.1

2. Use Pip To Install Selenium Python Module.

192:~ $ pip install selenium Collecting selenium Downloading https://files.pythonhosted.org/packages/b8/53/9cafbb616d20c7624ff31bcabd82e5cc9823206267664e68aa8acdde4629/selenium-3.14.0-py2.py3-none-any.whl (898kB) 100% |████████████████████████████████| 901kB 714kB/s Requirement already satisfied: urllib3 in ./anaconda3/lib/python3.6/site-packages (from selenium) (1.22) Installing collected packages: selenium Successfully installed selenium-3.14.0

3. Create Django Project And Startup Django Web Server.

  1. Open a terminal and input the below command in your working directory. $ django-admin.py startproject TodoList
  2. Run ls -l command, then you can find the directory TodoList under the current working folder.
  3. CD into the TodoList folder, there is a folder also named TodoList and a file manage.py. The inside TodoList folder is the place where all these webserver project files are saved, the manage.py file is the Django webserver management file. The _pycache_ folder is the cache folder for all the project python source files.
    python-django-web-project-files-structure-new
  4. To start up the Django project web server, please run the below command. 192:TodoList $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 30, 2018 - 16:01:58 Django version 2.1, using settings 'TodoList.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
  5. Now the Django web server has been created and started up, open a web browser and access url  http://127.0.0.1:8000/ to see the Django project welcome page.

4. Run Selenium In Python Code To Test Above Django Server.

  1. Now save the below code in a file TestDjango.py and execute python TestDjango.py in a terminal, you can get the error message in the console. from selenium import webdriver import time   def assert_django_title():   # Create the Firefox web browser browser = webdriver.Firefox(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/geckodriver')   # Access the Django web server home page. browser.get('http://127.0.0.1:8000/')   # Assert the web page title, the web page title do not contains Djangl so you can see error message in the console. assert 'Django' in browser.title   # Sleep 10 seconds. time.sleep(10)   # Close and quit the Firefox web browser browser.quit()   if __name__ == '__main__': assert_django_title()

5. Use Python Unittest Module To Test Django Home Page Title.

    1. Python unittest module tests the Django home page title example source code. from selenium import webdriver import time import unittest   class DjangoTest(unittest.TestCase):   # This method is invoked when test case start. def setUp(self): # Create the Firefox browser when test case setup. self.browser = webdriver.Firefox(executable_path = '/Users/zhaosong/Documents/WorkSpace/tool/geckodriver')   # This method is invoked when test case complete. def tearDown(self): # Close and quit the Firefox browser when test case tear down. self.browser.quit()   # This is the test method. def testHomePage(self): # Get Django home page. self.browser.get('http://127.0.0.1:8000/') # Sleep 10 seconds to wait for the page load. time.sleep(10) # Assert whether the web page title contains word Djangl or not. self.assertIn("Djangl", self.browser.title, 'Browser title do not contains Django')   if __name__ == '__main__': # Runn all test case function. unittest.main()
    2. Run above python code will get the below error message in the console. ====================================================================== FAIL: testHomePage (__main__.DjangoTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/selenium/SeleniumDjangoExample.py", line 23, in testHomePage self.assertIn("Djangl", self.browser.title, 'Browser title do not contains Django') AssertionError: 'Djangl' not found in 'Django: the Web framework for perfectionists with deadlines.' : Browser title do not contains Django ---------------------------------------------------------------------- Ran 1 test in 15.181s FAILED (failures=1)


selenium用法详解 selenium主要是用来做自动化测试,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题。 模拟浏览器进行网页加载,当requests,urllib无法正常获取网页内容的时候 一、声明浏览器对象 注意点一,Python文件名或者包名不要命名为selenium,会导致无法导入 from selenium import webdriver #webdriver可以认为是浏览器的驱动器,要驱动浏览器必须用到webdriver,支持多种浏览器,这里以Chrome为例 browser = webdriver.Chrome() 二、访问页面并获取网页html from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.taobao.com') print(browser.page_source)#browser.page_source是获取网页的全部html browser.close() 三、查找元素 单个元素 from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.taobao.com') input_first = browser.find_element_by_id('q') input_second = browser.find_element_by_css_selector('#q') input_third = browser.find_element_by_xpath('//*[@id="q"]') print(input_first,input_second,input_third) browser.close() 常用的查找方法 find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector 也可以使用通用的方法 from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Chrome() browser.get('https://www.taobao.com') input_first = browser.find_element(BY.ID,'q')#第一个参数传入名称,第二个传入具体的参数 print(input_first) browser.close() 多个元素,elements多个s input_first = browser.find_elements_by_id('q') 四、元素交互操作-搜索框传入关键词进行自动搜索 from selenium import webdriver import time browser = webdriver.Chrome() browser.get('https://www.taobao.com') input = browser.find_element_by_id('q')#找到搜索框 input.send_keys('iPhone')#传送入关键词 time.sleep(5) input.clear()#清空搜索框 input.send_keys('男士内裤') button = browser.find_element_by_class_name('btn-search')#找到搜索按钮 button.click() 更多操作: http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement#可以有属性、截图等等 五、交互动作,驱动浏览器进行动作,模拟拖拽动作,将动作附加到动作链中串行执行 from selenium import webdriver from selenium.webdriver import ActionChains#引入动作链 browser = webdriver.Chrome() url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' browser.get(url) browser.switch_to.frame('iframeResult')#切换到iframeResult框架 source = browser.find_element_by_css_selector('#draggable')#找到被拖拽对象 target = browser.find_element_by_css_selector('#droppable')#找到目标 actions = ActionChains(browser)#声明actions对象 actions.drag_and_drop(source, target) actions.perform()#执行动作 更多操作: http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains 六、执行JavaScript 有些动作可能没有提供api,比如进度条下拉,这时,我们可以通过代码执行JavaScript from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.zhihu.com/explore') browser.execute_script('window.scrollTo(0, document.body.scrollHeight)') browser.execute_script('alert("To Bottom")') 七、获取元素信息 获取属性 from selenium import webdriver from selenium.webdriver import ActionChains browser = webdriver.Chrome() url = 'https://www.zhihu.com/explore' browser.get(url) logo = browser.find_element_by_id('zh-top-link-logo')#获取网站logo print(logo) print(logo.get_attribute('class')) browser.close() 获取文本值 from selenium import webdriver browser = webdriver.Chrome() url = 'https://www.zhihu.com/explore' browser.get(url) input = browser.find_element_by_class_name('zu-top-add-question') print(input.text)#input.text文本值 browser.close() # 获取Id,位置,标签名,大小 from selenium import webdriver browser = webdriver.Chrome() url = 'https://www.zhihu.com/explore' browser.get(url) input = browser.find_element_by_class_name('zu-top-add-question') print(input.id)#获取id print(input.location)#获取位置 print(input.tag_name)#获取标签名 print(input.size)#获取大小 browser.close() 八、Frame操作 frame相当于独立的网页,如果在父类网frame查找子类的,则必须切换到子类的frame,子类如果查找父类也需要先切换 from selenium import webdriver from selenium.common.exceptions import NoSuchElementException browser = webdriver.Chrome() url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' browser.get(url) browser.switch_to.frame('iframeResult') source = browser.find_element_by_css_selector('#draggable') print(source) try: logo = browser.find_element_by_class_name('logo') except NoSuchElementException: print('NO LOGO') browser.switch_to.parent_frame() logo = browser.find_element_by_class_name('logo') print(logo) print(logo.text) 九、等待 隐式等待 当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常, 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0 from selenium import webdriver browser = webdriver.Chrome() browser.implicitly_wait(10)#等待十秒加载不出来就会抛出异常,10秒内加载出来正常返回 browser.get('https://www.zhihu.com/explore') input = browser.find_element_by_class_name('zu-top-add-question') print(input) 显式等待 指定一个等待条件,和一个最长等待时间,程序会判断在等待时间内条件是否满足,如果满足则返回,如果不满足会继续等待,超过时间就会抛出异常 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Chrome() browser.get('https://www.taobao.com/') wait = WebDriverWait(browser, 10) input = wait.until(EC.presence_of_element_located((By.ID, 'q'))) button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-search'))) print(input, button) title_is 标题是某内容 title_contains 标题包含某内容 presence_of_element_located 元素加载出,传入定位元组,如(By.ID, 'p') visibility_of_element_located 元素可见,传入定位元组 visibility_of 可见,传入元素对象 presence_of_all_elements_located 所有元素加载出 text_to_be_present_in_element 某个元素文本包含某文字 text_to_be_present_in_element_value 某个元素值包含某文字 frame_to_be_available_and_switch_to_it frame加载并切换 invisibility_of_element_located 元素不可见 element_to_be_clickable 元素可点击 staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新 element_to_be_selected 元素可选择,传元素对象 element_located_to_be_selected 元素可选择,传入定位元组 element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False alert_is_present 是否出现Alert 详细内容:http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions 十一、前进后退-实现浏览器的前进后退以浏览不同的网页 import time from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.baidu.com/') browser.get('https://www.taobao.com/') browser.get('https://www.python.org/') browser.back() time.sleep(1) browser.forward() browser.close() 十二、Cookies from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.zhihu.com/explore') print(browser.get_cookies()) browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'}) print(browser.get_cookies()) browser.delete_all_cookies() print(browser.get_cookies()) 选项卡管理 增加浏览器窗口 import time from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.baidu.com') browser.execute_script('window.open()') print(browser.window_handles) browser.switch_to_window(browser.window_handles[1]) browser.get('https://www.taobao.com') time.sleep(1) browser.switch_to_window(browser.window_handles[0]) browser.get('http://www.fishc.com') 十三、异常处理 from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.baidu.com') browser.find_element_by_id('hello') from selenium import webdriver from selenium.common.exceptions import TimeoutException, NoSuchElementException browser = webdriver.Chrome() try: browser.get('https://www.baidu.com') except TimeoutException: print('Time Out') try: browser.find_element_by_id('hello') except NoSuchElementException: print('No Element') finally: browser.close() # 详细文档:http://selenium-python.readthedocs.io/api.html#module-selenium.common.exceptions

标签:webdriver,get,selenium,element,import,browser
From: https://www.cnblogs.com/lxgbky/p/17545360.html

相关文章

  • bs4、selenium的使用
    爬取新闻#1爬取网页---requests#2解析 ---xml格式,用了re匹配的 ---html,bs4,lxml。。。---json: -python:内置的 -java:fastjson---》漏洞-java:谷歌Gson-go:内置基于反射,效率不高#pip3.8installbeautifulsoup4#pip3.8instal......
  • Selenium Grid
       用于在不同机器,不同浏览器的并行测试工具工作原理:seleniumscripts发送请求调用hub节点,然后通过hub节点分发到具体的测试用例到node节点执行环境搭建:1、文件准备https://selenium-release.storage.googleapis.com/index.html下载selenium-server-standalone的jar包(安......
  • Selenium基础:SSL证书错误处理 13
    1、chrome解决办法在chromeoptions()中添加”--ignore-certificate-errors"为true的选项#-*-coding:utf-8-*-fromseleniumimportwebdriveroptions=webdriver.ChromeOptions()#添加忽视证书错误选项options.add_argument('--ignore-certificate-errors')driver=web......
  • Anaconda环境下使用pip install selenium安装失败的解决办法
    背景:在Anaconda环境下执行pipinstallselenium,一直报timeout错误 解决方法:python-mpipinstallselenium 参考资料:https://blog.csdn.net/qq_45538469/article/details/113872262TRANSLATEwithxEnglishArabicHebrewPolishBulgarianHindiP......
  • Selenium基础:配置chrome浏览器 12
    1、屏蔽浏览器对selenium的检测”chrome正受到自动测试软件的控制。“解决方法:options=webdriver.ChromeOptions()options.add_experimental_option('excludeSwitches',['enable-automation'])driver=webdriver.Chrome(options=options)2、禁止图片和视频加载optio......
  • Selenium基础:其他设置 11
    1、限制页面加载时间设置页面加载限制时间:set_page_load_timeout(time)#-*-coding:utf-8-*-fromseleniumimportwebdriverfromselenium.common.exceptionsimportTimeoutExceptiondriver=webdriver.Chrome()#限制页面加载时间为30sdriver.set_page_load_timeout(30......
  • selenium优雅打开并关闭网页
    with上下文管理器在python中是这样介绍的所有实现了__enter____exit__dundermethod魔术方法的对象都可以用with接下来以Chrome为例查看底层def__enter__(self):returnselfdef__exit__(self,exc_type:typing.Optional[typing.Type[BaseExcept......
  • [-002-]-Python3+Unittest+Selenium Web UI自动化测试之显示等待WebDriverWait
    1、WebDriverWait基本用法引入包#文件引入fromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasEC每0.5s定位ID为userid的元素,如果定位成功,执行下面的代码;直至15s超时抛出异常可用来检查页面元素是......
  • Python错误:selenium自带click方法点击不到元素
    问题描述:selenium自带click方法,有的时候不好用,元素定位到了,但是就是点不上。 解决办法:原因分析:点击不到元素!解决办法:(1).selenium自带的click()方法:fromseleniumimportwebdriverel=driver.find_element(By.ID,ID)#找到元素el.click()#执行点击缺陷:不稳定......
  • selenium ui自动化遇到切换窗口,点击高级并继续访问的处理方式
    在python自动化中(ui),遇到了一个需要浏览器切换窗口,点击“高级”-“接受风险并继续”的操作,前期在本地编写代码调试时,没有任何问题。切换环境,放到Linux服务中,使用无头模式去运行代码时,发现切换窗口时,总是找不到页面元素,查看截图发现页面为空白,检查两天无果。场景图片,如下图所示,当......