Python+Selenium实现滑块|下拉框

一、实现滑块

Python+Selenium实现滑块|下拉框_第1张图片

Python+Selenium实现滑块|下拉框_第2张图片

#  跟网络状况有关,可以适当的sleep(3)
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains

# 打开浏览器并加载项目地址-->携程注册页面
driver = webdriver.Chrome()
driver.get("https://passport.ctrip.com/user/reg/home")
sleep(2)

# 点击同意并继续-->css定位   . 类  # id  >
element_agree = driver.find_element_by_css_selector("div.pop_footer>a.reg_btn.reg_agree")
element_agree.click()

# 定位滑块的位置
# ActionChains.drag_and_drop_by_offset(开始移动的元素-->原始元素,鼠标对元素拖拽到另一个元素的x坐标,鼠标对元素拖拽到另一个元素的y坐标)

element_hk = driver.find_element_by_css_selector("div.cpt-drop-box>div.cpt-drop-btn")
print(element_hk.size)  #  字典类型 {'height': 40, 'width': 40}
print(element_hk.size["height"], element_hk.size["width"])

# 定位滑块条的位置
element_hkt = driver.find_element_by_css_selector("div.cpt-drop-box>div.cpt-bg-bar")
print(element_hkt.size)
print(element_hkt.size["height"], element_hkt.size["width"])
sleep(3)
# 实现滑块
x_location = element_hk.size["width"] + element_hkt.size["width"]  # 注意x的坐标
y_location = element_hkt.size["height"]
sleep(3)
ActionChains(driver).drag_and_drop_by_offset(element_hk, x_location, y_location).perform()
driver.close()

 二、实现下拉框

Python+Selenium实现滑块|下拉框_第3张图片

# 鼠标移动事件
driver2 = webdriver.Chrome()
driver2.get("https://www.taobao.com/")
sleep(3)

# 鼠标移动到元素(中国大陆)上
element_1 = driver2.find_element_by_css_selector("div.site-nav-menu-hd>span.site-nav-region")
ActionChains(driver2).move_to_element(element_1).perform()
element_2 = driver2.find_element_by_css_selector("div.site-nav-menu-bd.site-nav-menu-list>ul#J_SiteNavRegionList>li:nth-child(3)")  # 兄弟节点  注意li:nth-child(3)的用法
element_2.click()
sleep(2)

 CSS ul li:nth-child的详细实例_jack_rose_me的博客-CSDN博客下面我将用几个典型的实例来给大家讲解:nth-child的实际用途:Tips:还用低版本的IE浏览器的哥们请绕过!1、取ul li 第一条 ul li:first-child 和 最后一条ul li:last-child2、指定取某条,ul li:nth-child(n),改变n的数字3、ul li:nth-child(n+3) 从大于等于3开始取值4、ul li:nth-child(n+3) 从小于等于3开始取值5、:nth-child(2n)选取偶数...https://blog.csdn.net/jack_rose_me/article/details/109386953

CSS3 :nth-child() 选择器 | 菜鸟教程CSS3 :nth-child() 选择器 完整CSS选择器参考手册 实例 指定每个 p 元素匹配的父元素中第 2 个子元素的背景色: [mycode3 type='css'] p:nth-child(2) { background:#ff0000; } [/mycode3] 尝试一下 » 定义和用法 :nth-child(n) 选择器匹配父元素中的第 n 个子元素,元素类型没有限制。 n ..https://www.runoob.com/cssref/sel-nth-child.html

 以上内容来自测码学院+个人补充整理

你可能感兴趣的:(web自动化,python,selenium)