代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import time
# 打开网络,登录,获取driver
def get_driver(url):
options = Options()
# 此步骤很重要,设置为开发者模式,防止被各大网站识别出来使用了Selenium
# options.add_experimental_option('excludeSwitches', ['enable-logging']) #禁止打印日志
options.add_experimental_option('excludeSwitches', ['enable-automation']) # 跟上面只能选一个
# options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) # 不加载图片,加快访问速度
# options.add_argument('--incognito') # 无痕隐身模式
# options.add_argument("disable-cache") # 禁用缓存
options.add_argument('disable-infobars') # 禁用“chrome正受到自动测试软件的控制”提示
options.add_argument('log-level=3') # INFO = 0 WARNING = 1 LOG_ERROR = 2 LOG_FATAL = 3 default is 0
# options.add_argument("--headless") # 无头模式--静默运行
options.add_argument("--window-size=1920,1080") # 使用无头模式,需设置初始窗口大小
options.add_argument("--test-type")
options.add_argument("--ignore-certificate-errors") # 与上面一条合并使用;忽略 Chrome 浏览器证书错误报警提示
options.add_argument("--disable-gpu") # 禁用GPU加速
options.add_argument("--no-first-run") # 不打开首页
options.add_argument("--no-default-browser-check") # 不检查默认浏览器
options.add_argument('--start-maximized') # 最大化
driver_path = "./chromedriver"
driver = webdriver.Chrome(executable_path=driver_path, options=options)
driver.get(url)
return driver
def search_baidu(search_text):
url = 'https://www.baidu.com'
driver = get_driver(url)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'kw'))).send_keys(search_text)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'su'))).click()
time.sleep(5)
driver.quit() # 关闭driver
if __name__ == "__main__":
search_baidu('csdn')
|