如何将 google 选项卡(已打开)附加到 python 脚本

问题描述 投票:0回答:1

我想打开将 python 脚本附加到已打开的 google 选项卡。

基本上,我的目标是在页面上执行一些操作,然后获取源代码。

我已经尝试使用硒,就像我在另一个主题中发现的那样,如下所示:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option('debuggerAddress', 'localhost:9014')
driver = webdriver.Chrome(options=options)

# Get the source code of the current page
source_code = driver.page_source

但是当我尝试启动它时,没有任何附加内容。这条线接缝被堵住了:

options.add_experimental_option('debuggerAddress', 'localhost:9014')

也许我输入了错误的端口?我不知道。

有人有另一种方法将 python 脚本附加到打开的谷歌选项卡,或解决“错误”。

python google-chrome selenium-webdriver web-scraping
1个回答
0
投票
  1. 关闭Chrome的所有实例。
  2. 打开CMD
  3. 使用远程调试端口启动Chrome,根据您的操作系统运行这些命令之一。

Windows

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9014

MacOS

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9014

Linux

google-chrome --remote-debugging-port=9014

确保:

  • 确保 ChromeDriver 和 Chrome 版本兼容。
  • 确保 ChromeDriver 在您系统的路径中。

这是脚本:

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option('debuggerAddress', 'localhost:9014')
driver = webdriver.Chrome(options=options)
source_code = driver.page_source
print(source_code)
© www.soinside.com 2019 - 2024. All rights reserved.