selenium常用操作

cooolr 于 2022-09-09 发布

**Selenium with Python中文翻译文档**

添加Cookie

cookie_dict = {
    'name': '',
    'value': 'test_tnaot_token=d5557adc-999d-4f91-9035-2b6c52ef08d0',
    
}

chrome.add_cookie(cookie_dict)
chrome.refresh()

鼠标移动

webdriver.ActionChains(chrome).move_to_element(chrome.find_element_by_xpath('//div[@id="image"]')).perform()
time.sleep(2)
chrome.find_element_by_xpath('//div[@id="image"]/button').click()

修改语言

chrome_options.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})

添加代理

options.add_argument("--proxy-server=http://192.168.1.92:10809")

滚动下滑

driver.execute_script("document.documentElement.scrollTop=10000")

执行JavaScript

text = "hello world"

res = driver.execute_script("return arguments[0]", text)

输入文字

driver.find_element_by_xpath('//input').send_keys('123456')

前进后退

# 后退
driver.back()
# 前进
driver.forward()
# 刷新
driver.refresh()

等待加载

driver.implicitly_wait(2)

清理缓存

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('chrome://settings/clearBrowserData')
driver.find_element_by_xpath('//settings-ui').send_keys(Keys.ENTER)
options.add_argument('--disable-application-cache')
options.add_argument('--disk-cache-size=0')
options.add_argument("--incognito")
driver.execute_cdp_cmd("Network.setCacheDisabled", {"cacheDisabled":True})
# 指定cache目录,再自动清理
options.add_argument(f"--disk-cache-dir=/tmp/cache")