Selenium 代理设置,页面等待,获取元素

代理设置、无头浏览器、显示等待隐式等待icon-default.png?t=N7T8https://blog.youkuaiyun.com/a6864657/article/details/80616418

1、implicitly_wait 隐式等待

# -*- coding:utf-8 -*-

"""
implicitly_wait():隐式等待
当使用了隐士等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常
换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0
一旦设置了隐式等待,则它存在整个 WebDriver 对象实例的声明周期中,隐式的等到会让一个正常响应的应用的测试变慢,
它将会在寻找每个元素的时候都进行等待,这样会增加整个测试执行的时间。
"""

from selenium import webdriver 
import time

driver = webdriver.Firefox()
driver.get('http://demo.tutorialzine.com/2009/09/simple-ajax-website-jquery/demo.html')

#等待10秒
driver.implicitly_wait(10)
driver.find_element_by_link_text("Page 4").click()

message = driver.find_element_by_id('pageContent')
#等待 Ajax 的内容出现
time.sleep(4)
print "Nunc nibh tortor" in message.text

2、设置加载超时

try:
    driver.set_page_load_timeout(30)
    driver.set_script_timeout(30)
    driver.get(url)
except:
    traceback.print_exc()
finally:
    driver.close()
    driver.quit()

3、获取元素等待

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException

def find_element_no_exception(ele, selector, wait = 10):
    try:
        return WebDriverWait(ele, wait).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, selector)))
    except Exception as e:
        return None

element = find_element_no_exception(driver, '#element-id', 5)

4、获取元素信息

x = driver.execute_script('return document.getElementsByClassName("class")[0].x')
# 获取多个链接
for link in driver.find_element(By.XPATH, "//*[@href]"):
    print(link.get_attribute('href'))
# 获取单个链接
driver.find_element(By.XPATH, "//*[@href]").get_attribute('href')

XPATH用法参考:

https://blog.youkuaiyun.com/abments/article/details/139922211icon-default.png?t=N7T8https://blog.youkuaiyun.com/abments/article/details/139922211CSS选择器参考:

https://blog.youkuaiyun.com/abments/article/details/139922211icon-default.png?t=N7T8https://blog.youkuaiyun.com/abments/article/details/139922211获取其他属性:

#获取元素标签的内容:
get_attribute('textContent')

#获取元素内的全部HTML:
get_attribute('innerHTML')

#获取包含选中元素的HTML:
get_attribute('outerHTML')

get_attribute('class')

get_attribute('name')

get_attribute('id')

get_attribute('href')

更多用法参考:

https://blog.youkuaiyun.com/qq_46158060/article/details/123323830icon-default.png?t=N7T8https://blog.youkuaiyun.com/qq_46158060/article/details/123323830

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值