使用Rselenium和Docker独立镜像进行Web抓取

wmomyfyw  于 8个月前  发布在  Docker
关注(0)|答案(1)|浏览(93)

我又一次读了很多关于这个问题的帖子,却无法理解......
我在Ubuntu 22.04操作系统上使用Rselenium和selenium独立镜像与Docker。
下面的代码在使用Docker镜像selenium/standalone-chrome-debug时运行良好:

system('docker run -d -p 4445:4444 selenium/standalone-chrome-debug')
remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L,
                      browserName = "chrome")
remDr$open()
remDr$navigate("https://fr.distance.to/paris/bayonne-france")
el <- remDr$findElement(using = "css", ".headerRoute > #strck > span:nth-child(1)")
road_distance <- el$getElementText()[[1]]
remDr$close()
system('docker rm -f $(docker ps -aq --filter ancestor=selenium/standalone-chrome-debug)')

然而,完全相同的代码,但使用selenium/standalone-chrome图像,在remDr$open()的第一步卡住,最终输出崩溃:

remDr$open()
[1] "Connecting to remote server"
$id
[1] NA

任何想法为什么以及如何解决这个问题?我真的不介意使用selenium/standalone-chrome映像的debug版本,但它似乎已被弃用,我很想了解这里发生了什么

aiazj4mn

aiazj4mn1#

我也遇到过同样的问题,你的帖子实际上很有帮助,因为它实际上允许我连接到standalone-chrome-debug docker容器。
我认为基本的问题是RSelenium已经很长时间没有更新了,并且使用的是Selenium版本2。碰巧的是,图像selenium/standalone-chrome-debug也很长时间没有更新了。我相信selenium/standalone-chrome镜像使用的是更新版本的Selenium API,而RSelenium代码在尝试使用旧的API来处理新镜像时失败了。
事实证明,使用Python Selenium绑定和R中的reticulate包连接到Docker容器非常容易。这里有一个对我有用的例子:

selenium_conn<-py_run_string("from selenium import webdriver
from selenium.webdriver.common.by import By

opts=webdriver.ChromeOptions()
# Set Chrome options so that PDFs download automatically
opts.add_experimental_option('prefs',
{  'profile.default_content_settings.popups' : 0,
 'download.default_directory' : '/opt/selenium/assets',
 'download.directory_upgrade' : True,
 'download.prompt_for_download' : False,
 'plugins.always_open_pdf_externally':True
}
)

browser = webdriver.Remote('http://localhost:4444', options=opts)
")

web_driver<-selenium_conn$browser

web_driver$get('http://medium.com')

相关问题