Python Selenium

from selenium import webdriver # 导入
from selenium.webdriver.common.by import By # 导入使用find_element用by的方法

wd = webdriver.Chrome() # 指定浏览器,创建WebDriver对象

wd.get("https://www.baidu.com") # 打开网页

element = wd.find_element(By.ID, "kw") # 根据ID选择元素,选择ID为kw"的元素,百度的kw元素为搜索输入框,如果没找到元素,会报错:NoSuchElementException
element.send_keys("123") # 输入值
element.click() # 点击element元素
wd.find_elements(By.CLASS_NAME, 'animal') # 找到多个元素,注意"element(s)"

for element in elements:
  print(element.text)
 
wd.quit() # 关闭浏览器

弹出Alert

driver.find_element(By.ID, 'b1').click()

# 判断是否有弹出框
try:
  alert = driver.switch_to.alert
  # 如果有弹出框,打印弹出框的内容
  print(alert.text)
  # 关闭弹出框
  driver.switch_to.alert.accept()
except:
  pass

切换iFrame

#切换至iFrame(页面只有一个iFrame)
wd.switch_to.frame(wd.find_element(By.TAG_NAME, "iframe"))
# 切换回主页面
wd.switch_to.default_content()

在Selenium中使用JavaScript

trigger_download = wd.execute_script(
  '''
  $('#begin_date').datebox('setValue','2023-04-01');
  $('#end_date').datebox('setValue','2023-04-31');
  downloadAction()
  ''')
posted @ 2023-04-16 01:56  chrjiajia  阅读(28)  评论(0)    收藏  举报