ubuntu下安装selenium

抓取动态网页的两种方式:
一、对动态网页进行逆向工程;
二、渲染动态网页。

因为有些网站使用Google Web Tookit(GWT)开发,它产生的JavaScript代码是机器生成的压缩版。还原网页的结果可能会过于冗长造成结果难以处理。实际上,可以通过使用浏览器渲染引擎避免这些工作,这种渲染引擎在显示网页时解析HTML、应用CSS样式并执行JavaScript语句的部分。

因此我们可以模仿浏览器,使用WebKit渲染引擎或是使用selenium,WebKit具有高度灵活性,selenium的灵活性相对差一点,但selenium的优势在于使用方便、简单易上手。下面就介绍一下selenium的安装及可能出现的问题。

  • 通过pip install selenium
from selenium import webdriver
driver = webdriver.Chrome()
在上面的语句中会报下面的错误(我们是安装了Google Chrome)。
driver = webdriver.Chrome()
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
.
.
.
/usr/lib/python3.5/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1550                                 err_msg += ': ' + repr(orig_executable)
-> 1551                     raise child_exception_type(errno_num, err_msg)
   1552                 raise child_exception_type(err_msg)

FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver'
.
.
.
WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

在网上的一些博客找到一些答案是通过apt安装

sudo apt-get install chromium-chromedriver

这样并没有解决问题,后来找到解决办法(原文链接:Running Selenium WebDriver python bindings in chrome):
1、Check you have installed latest version of chrome brwoser-> chromium-browser -version
2、If not, install latest version of chrome sudo apt-get install chromium-browser
3、get appropriate version of chrome driver from here
4、Unzip the chromedriver.zip
5、Move the file to /usr/bin directory sudo mv chromedriver /usr/bin
6、Goto /usr/bin directory and you would need to run something like chmod a+x chromedriver to mark it executable.

通过这个方法成功解决问题,分析了一下原因,selenium需要Google chromium浏览器的支持,而不是Google chrome(虽然都是chrome浏览器)。

但是又出现了Can not connect to Service chromedriver这个问题,
在检查/etc/hosts文件时发现127.0.0.1在上次的终端问题中把localhost改成了我的主机名,只需要再添加一行127.0.0.1 localhost即可。

参考文献:
1、ubuntu14.04学习selenium之一:安装
2、Can not connect to Service chromedriver

猜你喜欢

转载自blog.csdn.net/qq_35882901/article/details/77642319