【发布时间】:2018-09-27 18:26:07
【问题描述】:
我在 python 中编写了一个 Selenium 脚本,并在 bash 中编写了一个安装程序,这样我就可以在另一台机器上使用该脚本(所有当前 OSX 的 Mac)。
这是安装程序中的相关内容(机器是全新的 Mac,所以首先需要安装任何感兴趣的东西):
#!/bin/bash
#get neccesities
xcode-select --install
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install wget
brew install chromedriver
export PATH=$PATH:/usr/local/bin/chromedriver
brew install git
# config git
git config --global credential.helper osxkeychain
git config --global user.name "SOMENAME"
git config --global user.email "SOMEMAIL"
#get virtualenv
sudo easy_install pip
sudo pip install virtualenv
#get chrome
wget https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg
open ~/googlechrome.dmg
sudo cp -r /Volumes/Google\ Chrome/Google\ Chrome.app /Applications/
sudo diskutil unmountDisk /dev/disk3
rm -Rf ~/googlechrome.dmg
#clone repo and setup the venv
cd somewhere
git clone some_repo.git
virtualenv env
source ./env/bin/activate
pip install -r requirements.txt
现在,这个安装程序在过去 2 个月内(或多或少)在三到四台机器上运行,但现在我似乎无法让脚本正常运行。当我尝试运行 file.py 时,出现以下错误:
Traceback (most recent call last):
File "file.py", line 56, in <module>
reminder.driver.quit()
AttributeError: MyReminder instance has no attribute 'driver'
实际问题在第 56 行之前,因为 chromedriver 永远不会打开 Chrome。
文件.py
from selenium import webdriver
class MyReminder:
def __init__(self,job):
self.job = job
def run(self):
options = webdriver.ChromeOptions()
options.add_argument("window-size=1280,960")
self.driver = webdriver.Chrome(chrome_options=options)
## do some stuff ##
reminder = MyReminder(job.id)
while True:
try:
reminder.run()
except:
reminder.driver.quit()
确切地说,这个 python 脚本目前可以在四台不同的机器上运行。我几乎确信问题出在 chromedriver/selenium/python 解释器/组合的某个地方,我只是不明白在哪里。
编辑:感谢有用的评论,我将reminder.run() 放在try-block 之外,以获得更简洁的回溯:
Traceback (most recent call last):
File "file.py", line 52, in <module>
reminder.run()
File "file.py", line 15, in run
self.driver = webdriver.Chrome(chrome_options=options)
File "/Users/.../env/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__
self.service.start()
File "/Users/.../env/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 102, in start
raise WebDriverException("Can not connect to the Service %s" % self.path)
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver`
我设法使用其他人已经给出的答案 here 解决了这个问题。
感谢您的帮助。
【问题讨论】:
-
你为什么要做两次
reminder.run(),一次在try里面,一次在外面? -
@Colin 我的错误、错误的复制和粘贴。我更正了。
-
MyReader是错字吗? -
天哪……抱歉。是的。我希望现在一切都好。
-
直到
run()成功完成后才会创建属性self.driver。在 try 语句引发错误的机器上,except 块尝试访问 as-of-yet uncreated 属性。在 try 块外运行reminder.run()以查看引发了什么错误并报告完整的回溯错误。
标签: python macos google-chrome selenium selenium-chromedriver