开发者

python打开浏览器并模拟搜索示例详解

开发者 https://www.devze.com 2023-11-19 12:17 出处:网络 作者: 雪狼骑兵
目录打开已存在的浏览器在cmd命令行下执行命令模拟打开百度,并进行搜索打开已存在的浏览器
目录
  • 打开已存在的浏览器
  • 在cmd命令行下执行命令
  • 模拟打开百度,并进行搜索

打开已存在的浏览器

打开已存在的浏览器有个很重要的作用就是,可以对于一些登录场景,提前登录好,不需要模拟登录了。

在命令行中执行打开chrome的命令,在图标上找到chrome的安装位置

python打开浏览器并模拟搜索示例详解

在cmd命令行下执行命令

C:\Program Files\Google\Chrome\Application>chrome.exe --remote-debugging-port=9222

此时调试模式会监听9222端口

模拟打开百度,并进行搜索

import time
from selenium iphpmport webdriver
from selenium.webdriver.common.keys import Kepythonys
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 impor编程客栈t 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("浏览器已打开"+browser.title)
    # 切换到前台
    Windows = gw.getWindowsWithTitle(browser.title)
    if len(windows) > 0:
        windows[0].activate()
    time.sleep(1)
    # 新建新标签
    browser.execute_script("window.open('');")
    browser.switch_to.window(browser.window_handles[-1])
   javascript time.sleep(2)
    # 在新标签页中打开一个URL
    browser.get('https://www.baidu.com/')
    # 输入搜索词并回车
    elem = browser.find_element(By.ID, "kw")
    elem.send_keys("唯一客服")
    elem.send_keys(Keys.RETURN)
    print(编程客栈"获取搜索列表:")
    # 使用WebDriverWait确保搜索结果已经加载
    WebDriverWait(browser, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, "//div[@id='content_left']//h3/a"))
    )
    # 获取所有的搜索结果标题
    results = browser.find_elements(By.XPATH, "//div[@id='content_left']//h3/a")
    for result in results:
        print(result.text)
    # 关闭标签
    browser.close()
except Exception as e:
    print("An error occurred:", e)

以上就是python打开浏览器并模拟搜索示例详解的详细内容,更多关于python打开浏览器模拟搜索的资料请关注编程客栈(www.devze.com)其它相关文章!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号