python打開(kāi)瀏覽器并模擬搜索示例詳解
打開(kāi)已存在的瀏覽器
打開(kāi)已存在的瀏覽器有個(gè)很重要的作用就是,可以對(duì)于一些登錄場(chǎng)景,提前登錄好,不需要模擬登錄了。
在命令行中執(zhí)行打開(kāi)chrome的命令,在圖標(biāo)上找到chrome的安裝位置
在cmd命令行下執(zhí)行命令
C:\Program Files\Google\Chrome\Application>chrome.exe --remote-debugging-port=9222
此時(shí)調(diào)試模式會(huì)監(jiān)聽(tīng)9222端口
模擬打開(kāi)百度,并進(jìn)行搜索
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options import pygetwindow as gw try: chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") browser = webdriver.Chrome(options=chrome_options) print("瀏覽器已打開(kāi)"+browser.title) # 切換到前臺(tái) windows = gw.getWindowsWithTitle(browser.title) if len(windows) > 0: windows[0].activate() time.sleep(1) # 新建新標(biāo)簽 browser.execute_script("window.open('');") browser.switch_to.window(browser.window_handles[-1]) time.sleep(2) # 在新標(biāo)簽頁(yè)中打開(kāi)一個(gè)URL browser.get('https://www.baidu.com/') # 輸入搜索詞并回車 elem = browser.find_element(By.ID, "kw") elem.send_keys("唯一客服") elem.send_keys(Keys.RETURN) print("獲取搜索列表:") # 使用WebDriverWait確保搜索結(jié)果已經(jīng)加載 WebDriverWait(browser, 10).until( EC.presence_of_all_elements_located((By.XPATH, "http://div[@id='content_left']//h3/a")) ) # 獲取所有的搜索結(jié)果標(biāo)題 results = browser.find_elements(By.XPATH, "http://div[@id='content_left']//h3/a") for result in results: print(result.text) # 關(guān)閉標(biāo)簽 browser.close() except Exception as e: print("An error occurred:", e)
以上就是python打開(kāi)瀏覽器并模擬搜索示例詳解的詳細(xì)內(nèi)容,更多關(guān)于python打開(kāi)瀏覽器模擬搜索的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Python實(shí)現(xiàn)搜索Google Scholar論文信息的示例代碼
- 編寫Python腳本來(lái)獲取Google搜索結(jié)果的示例
- Python flashtext文本搜索和替換操作庫(kù)功能使用探索
- Python快速進(jìn)修指南之向量數(shù)據(jù)庫(kù)文本搜索
- AI與Python人工智能啟發(fā)式搜索概念理解
- python高級(jí)搜索實(shí)現(xiàn)高效搜索GitHub資源
- python實(shí)現(xiàn)精準(zhǔn)搜索并提取網(wǎng)頁(yè)核心內(nèi)容
- python GoogleIt庫(kù)實(shí)現(xiàn)在Google搜索引擎上快速搜索
相關(guān)文章

Python3中urllib庫(kù)添加請(qǐng)求頭的兩種方式

python如何實(shí)現(xiàn)最小矩形覆蓋問(wèn)題

Python二叉搜索樹與雙向鏈表轉(zhuǎn)換實(shí)現(xiàn)方法

Python3使用requests模塊實(shí)現(xiàn)顯示下載進(jìn)度的方法詳解

解決使用pycharm提交代碼時(shí)沖突之后文件丟失找回的方法

用Python進(jìn)行柵格數(shù)據(jù)的分區(qū)統(tǒng)計(jì)和批量提取

Python中optparser庫(kù)用法實(shí)例詳解