日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

selenium2与python自动化6-select下拉框

發布時間:2025/3/20 python 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 selenium2与python自动化6-select下拉框 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先來認識一些select,在白百度搜索頁面中


點擊“搜索設置”按鈕


? ? ? ?箭頭所指的即為select搜索框,使用firebug打開元素定位,select標簽下有三個選項,這樣首先通過select標簽的id定位到select層級,接著對于子選項需要進行二次定位。那如何進行二次定位呢?

  • 定位select下拉框
  • 定位select中的子選項
  • #coding:utf-8 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChainsdriver = webdriver.Firefox() URL = "http://www.baidu.com" driver.maximize_window() driver.get(URL)driver.implicitly_wait(10)#鼠標移動到“設置"按鈕 mouse = driver.find_element_by_link_text(u"設置") ActionChains(driver).move_to_element(mouse).perform()driver.find_element_by_link_text(u"搜索設置").click()#先定位下拉框,再定位選項 s = driver.find_element_by_id("nr") s.find_element_by_xpath("//option[@value='50']").click()

    或者將后兩步合并為一步進行元素定位

    driver.find_element_by_xpath(".//*[@id='nr']/option[2]").click()

    這里的選項索引是從1開始的,需要注意。

    除此之外,還可以使用select模塊進行元素,首先導入相應的模塊,直接根據屬性或者索引進行元素定位

    from selenium.webdriver.support.select import Select通過選項的索引來定位到對應的選項,選項索引是0開始
    #coding:utf-8 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.select import Selectdriver = webdriver.Firefox() URL = "http://www.baidu.com" driver.maximize_window() driver.get(URL)driver.implicitly_wait(10)#鼠標移動到“設置"按鈕 mouse = driver.find_element_by_link_text(u"設置") ActionChains(driver).move_to_element(mouse).perform()driver.find_element_by_link_text(u"搜索設置").click()#先定位下拉框,再定位選項 #s = driver.find_element_by_id("nr") #s.find_element_by_xpath("//option[@value='50']").click() #driver.find_element_by_xpath(".//*[@id='nr']/option[3]").click()s = driver.find_element_by_id("nr") Select(s).select_by_index(2)

    通過select_by_index(2)定位到選項中“每頁顯示50條”,此外還可以使用select模塊中的value進行定位,我們知道在select下拉框中,分別是:每頁顯示10條,20條,50條,通過value=10,20,50進行選擇

    Select(s).select_by_value("20")

    也可以通過文本內容進行定位,話不多說

    Select(s).select_by_visible_text("每頁顯示50條")

    其他的常用函數有:

    select_by_index()? :通過索引定位
    select_by_value()? :通過value值定位
    select_by_visible_text() :通過文本值定位
    deselect_all()????????? :取消所有選項
    deselect_by_index()???? :取消對應index選項
    deselect_by_value()????? :取消對應value選項
    deselect_by_visible_text() :取消對應文本選項
    first_selected_option()? :返回第一個選項
    all_selected_options()?? :返回所有的選項

    總結

    以上是生活随笔為你收集整理的selenium2与python自动化6-select下拉框的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。