from selenium.webdriver.common.action_chains import ActionChains from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC #期望条件 from selenium.webdriver.common.by import By #八种定位方式 from selenium.webdriver.common.keys import Keys ''' 1.创建浏览器驱动 2.访问网站 3.操作事件(如:点击登录按钮) 4.等待下一个事件出现之前需要等待(一般用显性等待) 5.等待结束后,操作下一个事件 6.需要操作iframe时需要先切换到iframe 7.切换结束后就可以操作事件 8.事件结束后想要退出iframe使用driver.switch_to.default_content ''' import time #创建浏览器驱动 driver = webdriver.Chrome(service_log_path='E:js.log') # driver.fullscreen_window() driver.maximize_window() # driver.implicitly_wait(30) #访问一个网站 driver.get('https://www.12306.cn/index/') #出发点和目的地 time.sleep(2) driver.find_element_by_id("fromStationText").click() # ActionChains(driver).move_to_element(driver.find_element_by_id("fromStationText")).perform() driver.find_element_by_id("fromStationText").send_keys("杭州") #在弹窗的详细框内点击 WebDriverWait(driver,5,1).until(EC.visibility_of_element_located((By.XPATH,"//span[contains(text(),'杭州南')]"))) driver.find_element_by_xpath("//span[contains(text(),'杭州南')]").click() time.sleep(0.5) driver.find_element_by_id("toStationText").send_keys('上海') #在弹窗的详细框内点击 WebDriverWait(driver,5,1).until(EC.visibility_of_element_located((By.XPATH,"//span[contains(text(),'上海虹桥')]"))) driver.find_element_by_xpath("//span[contains(text(),'上海虹桥')]").click() time.sleep(0.5) #js使用,在一个文本框内如果是只读的情况下需要改变他的属性为false或者删除 js = "var ele = document.getElementById('train_date');ele.removeAttribute('readonly');ele.value='2020-08-26';document.getElementById('search_one').click();" driver.execute_script(js) #执行js代码