gpt4 book ai didi

python - selenium webdriver.Firefox 不为非 sudo 用户启动

转载 作者:IT王子 更新时间:2023-10-29 01:26:54 28 4
gpt4 key购买 nike

我有一个 python 方法,可以在 linux 服务器上以 headless 模式设置浏览器,以便使用 selenium 抓取网站。无论哪个用户执行 python 脚本,显示设置都非常好,但如果 sudo 用户不执行脚本,它将卡在 webdriver.Firefox() 设置无限期地行。

这是完整的方法:

def browserSetup(self, browser=None):
try:
# now Firefox will run in a virtual display. you will not see the browser.
self.display = Display(visible=0, size=(800, 600))
self.display.start()

if self.verbose:
print "Virtual display started for browser instantiation."

#change user agent
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1")
profile.set_preference("webdriver.log.file", "webdriver.log")

# Create a new instance of the Firefox driver
browser = webdriver.Firefox(profile)

if self.verbose:
print "Browser window object established @ %s." % browser

return browser
except Exception, e:
raise e

因此,重复我的问题:如果脚本未作为 sudo 执行,则脚本将在 webdriver.Firefox 创建时无限期挂起线。为什么会这样?

更新:问题是这里的这一行:

 browser = webdriver.Firefox() #with or without the profile variable - the results are the same

再次更新下面评论中的几个人建议我尝试从命令行手动运行 Firefox 以查看是否有任何问题;这是结果:

#initialize the virtual display
$ sudo Xvfb :10 -extension RANDR
[dix] Could not init font path element /usr/share/fonts/X11/cyrillic, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/100dpi/:unscaled, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/75dpi/:unscaled, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/Type1, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/100dpi, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/75dpi, removing from list!
[dix] Could not init font path element /var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType, removing from list!

#now start firefox in another ssh window (since the Xvfb process is consuming my prompt)
$ export DISPLAY=:10
$ firefox

(firefox:6347): GConf-WARNING **: Client failed to connect to the D-BUS daemon:
//bin/dbus-launch terminated abnormally without any error message

最后一条错误消息显示数百次...

最佳答案

我只能猜测,但这是我怀疑的。

sudo 会在您通过它启动 Firefox 时清除您的环境变量。这也包括 DISPLAY 变量。

禁用此行为的两种方法:- 在您的 sudoers 配置中禁用 env_reset。- 使用 sudo -i,这将保留 DISPLAY 的值。

关于python - selenium webdriver.Firefox 不为非 sudo 用户启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058409/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com