标签归档:selenium

错误消息:“’chromedriver’可执行文件必须在路径中可用”

问题:错误消息:“’chromedriver’可执行文件必须在路径中可用”

我正在将硒与python结合使用,并已从以下站点下载了适用于Windows计算机的chromedriver:http ://chromedriver.storage.googleapis.com/index.html?path=2.15 /

下载zip文件后,我将zip文件解压缩到我的下载文件夹中。然后,我将可执行二进制文件(C:\ Users \ michael \ Downloads \ chromedriver_win32)的路径放入环境变量“路径”中。

但是,当我运行以下代码时:

  from selenium import webdriver

  driver = webdriver.Chrome()

…我不断收到以下错误消息:

WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at     http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver

但是-如上所述-可执行文件在路径中是(!)…这里发生了什么?

I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: http://chromedriver.storage.googleapis.com/index.html?path=2.15/

After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\Downloads\chromedriver_win32) into the Environment Variable “Path”.

However, when I run the following code:

  from selenium import webdriver

  driver = webdriver.Chrome()

… I keep getting the following error message:

WebDriverException: Message: 'chromedriver' executable needs to be available in the path. Please look at     http://docs.seleniumhq.org/download/#thirdPartyDrivers and read up at http://code.google.com/p/selenium/wiki/ChromeDriver

But – as explained above – the executable is(!) in the path … what is going on here?


回答 0

您可以测试它是否确实在PATH中,如果您打开cmd并输入chromedriver(假设您的chromedriver可执行文件仍以此命名),然后按Enter。如果Starting ChromeDriver 2.15.322448显示,则PATH设置正确,并且还有其他问题。

另外,您可以像这样使用chromedriver的直接路径:

 driver = webdriver.Chrome('/path/to/chromedriver') 

因此,在您的特定情况下:

 driver = webdriver.Chrome("C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

You can test if it actually is in the PATH, if you open a cmd and type in chromedriver (assuming your chromedriver executable is still named like this) and hit Enter. If Starting ChromeDriver 2.15.322448 is appearing, the PATH is set appropriately and there is something else going wrong.

Alternatively you can use a direct path to the chromedriver like this:

 driver = webdriver.Chrome('/path/to/chromedriver') 

So in your specific case:

 driver = webdriver.Chrome("C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

回答 1

我看到讨论仍在讨论通过下载二进制文件并手动配置路径来设置chromedriver的旧方法。

可以使用webdriver-manager自动完成

pip install webdriver-manager

现在,问题中的上述代码将可以在下面的更改中简单地工作,

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

可以使用相同的方法来设置Firefox,Edge和二进制文件。

I see the discussions still talk about the old way of setting up chromedriver by downloading the binary and configuring the path manually.

This can be done automatically using webdriver-manager

pip install webdriver-manager

Now the above code in the question will work simply with below change,

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

The same can be used to set Firefox, Edge and ie binaries.


回答 2

pycharm社区版的情况与此相同,因此对于cmd,必须重新启动ide才能重新加载路径变量。重新启动您的ide,应该没问题。

Same situation with pycharm community edition, so, as for cmd, you must restart your ide in order to reload path variables. Restart your ide and it should be fine.


回答 3

在Linux(Ubuntu或Debian)上:

sudo apt install chromium-chromedriver

在macOS上安装https://brew.sh/然后执行

brew cask install chromedriver

On Ubuntu:

sudo apt install chromium-chromedriver

On Debian:

sudo apt install chromium-driver

On macOS install https://brew.sh/ then do

brew cask install chromedriver

回答 4

r对于原始字符串,我们必须添加路径字符串,以字符串之前的字母开头。我以这种方式进行了测试,并且有效。

driver = webdriver.Chrome(r"C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

We have to add path string, begin with the letter r before the string, for raw string. I tested this way, and it works.

driver = webdriver.Chrome(r"C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

回答 5

一些额外的输入/说明,供以后使用该线程的读者使用,以避免修改PATH env。Windows级别的变量并重新启动Windows系统:(从https://stackoverflow.com/a/49851498/9083077复制我的答案,适用于Chrome):

(1)下载chromedriver(如本主题前面所述),然后将(解压缩的)chromedriver.exe放在X:\ Folder \ of \ your \ choice中

(2)Python代码示例:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Chrome();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

注意:(1)示例代码(在引用的答案中)可能需要5秒钟打开Firefox浏览器以获取指定的URL。(2)如果尚无服务器在指定的url上运行或提供标题为字符串’Django’的页面,则python控制台将显示以下错误:在browser.title AssertionError中断言’Django’。

Some additional input/clarification for future readers of this thread, to avoid tinkering with the PATH env. variable at the Windows level and restart of the Windows system: (copy of my answer from https://stackoverflow.com/a/49851498/9083077 as applicable to Chrome):

(1) Download chromedriver (as described in this thread earlier) and place the (unzipped) chromedriver.exe at X:\Folder\of\your\choice

(2) Python code sample:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Chrome();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notes: (1) It may take about 5 seconds for the sample code (in the referenced answer) to open up the Firefox browser for the specified url. (2) The python console would show the following error if there’s no server already running at the specified url or serving a page with the title containing the string ‘Django’: assert ‘Django’ in browser.title AssertionError


回答 6

对于Linux和OSX

步骤1:下载chromedriver

# You can find more recent/older versions at http://chromedriver.storage.googleapis.com/
# Also make sure to pick the right driver, based on your Operating System
wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip

第2步:将chromedriver添加到 /usr/local/bin

unzip chromedriver_mac64.zip
cp chromedriver /usr/local/bin

您现在应该可以运行

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('http://localhost:8000')

没有任何问题

For Linux and OSX

Step 1: Download chromedriver

# You can find more recent/older versions at http://chromedriver.storage.googleapis.com/
# Also make sure to pick the right driver, based on your Operating System
wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip

For debian: wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip

Step 2: Add chromedriver to /usr/local/bin

unzip chromedriver_mac64.zip
sudo mv chromedriver /usr/local/bin
sudo chown root:root /usr/local/bin/chromedriver
sudo chmod +x /usr/local/bin/chromedriver

You should now be able to run

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('http://localhost:8000')

without any issues


回答 7

解压缩chromedriver时,请务必指定确切位置,以便以后进行跟踪。在下面,您将为您的操作系统找到合适的chromedriver,然后将其解压缩到一个确切的位置,稍后可以在代码中将其作为参数提供。

wget http://chromedriver.storage.googleapis.com/2.10/chromedriver_linux64.zip unzip chromedriver_linux64.zip -d /home/virtualenv/python2.7.9/

When you unzip chromedriver, please do specify an exact location so that you can trace it later. Below, you are getting the right chromedriver for your OS, and then unzipping it to an exact location, which could be provided as argument later on in your code.

wget http://chromedriver.storage.googleapis.com/2.10/chromedriver_linux64.zip unzip chromedriver_linux64.zip -d /home/virtualenv/python2.7.9/


回答 8

如果您正在使用机器人框架RIDE。然后,您可以Chromedriver.exe从其官方网站下载并将此.exe文件保存在C:\Python27\Scripts目录中。现在将此路径作为环境变量提及。C:\Python27\Scripts\chromedriver.exe

重新启动计算机,然后再次运行相同的测试用例。您不会再遇到此问题。

If you are working with robot framework RIDE. Then you can download Chromedriver.exe from its official website and keep this .exe file in C:\Python27\Scripts directory. Now mention this path as your environment variable eg. C:\Python27\Scripts\chromedriver.exe.

Restart your computer and run same test case again. You will not get this problem again.


回答 9

根据说明,您需要在实例化webdriver时包括ChromeDriver的路径。Chrome例如:

driver = webdriver.Chrome('/path/to/chromedriver')

According to the instruction, you need to include the path to ChromeDriver when instantiating webdriver.Chrome eg.:

driver = webdriver.Chrome('/path/to/chromedriver')

回答 10

在将chromedriver添加到路径之前,请确保它与浏览器的版本相同。

如果不是,则需要匹配版本:更新/降级chrome,以及升级/降级webdriver。

我建议您尽可能多地更新Chrome版本,并匹配网络驱动程序。

要更新Chrome:

  • 在右上角,单击三个点。
  • 点击help->About Google Chrome
  • 更新版本并重新启动chrome

然后从此处下载兼容版本:http : //chromedriver.chromium.org/downloads

注意:最新的chromedriver并不总是与最新版本的chrome匹配!

现在,您可以将其添加到PATH中:

  1. 在您计算机的某个位置创建一个新文件夹,您将在其中放置Web驱动程序。我创建了一个命名的文件夹webdriversC:\Program Files

  2. 复制文件夹路径。就我而言C:\Program Files\webdrivers

  3. 右键单击this PC-> properties

  1. 在右键上 Advanced System settings
  2. 请点击 Environment Variables
  3. 在中System variables,单击,path然后单击edit
  4. 点击 new
  5. 粘贴之前复制的路径
  6. 在所有窗口上单击确定

而已!我使用了pycharm,不得不重新打开它。也许与其他IDE或终端相同。

Before you add the chromedriver to your path, make sure it’s the same version as your browser.

If not, you will need to match versions: either update/downgrade you chrome, and upgrade/downgrade your webdriver.

I recommend updating your chrome version as much as possible, and the matching the webdriver.

To update chrome:

  • On the top right corner, click on the three dots.
  • click help -> About Google Chrome
  • update the version and restart chrome

Then download the compatible version from here: http://chromedriver.chromium.org/downloads .

Note: The newest chromedriver doesn’t always match the newest version of chrome!

Now you can add it to the PATH:

  1. create a new folder somewhere in your computer, where you will place your web drivers. I created a folder named webdrivers in C:\Program Files

  2. copy the folder path. In my case it was C:\Program Files\webdrivers

  3. right click on this PC -> properties:

  1. On the right click Advanced System settings
  2. Click Environment Variables
  3. In System variables, click on path and click edit
  4. click new
  5. paste the path you copied before
  6. click OK on all the windows

Thats it! I used pycharm and I had to reopen it. Maybe its the same with other IDEs or terminals.


回答 11

如果您完全确定PATH设置正确,可以尝试重新启动计算机,如果它无法正常工作。

就Windows 7而言,我总是在WebDriverException上出现错误:消息:对于chromedriver,gecodriver,IEDriverServer。我很确定我有正确的路径。重启电脑,一切正常

Could try to restart computer if it doesn’t work after you are quite sure that PATH is set correctly.

In my case on windows 7, I always got the error on WebDriverException: Message: for chromedriver, gecodriver, IEDriverServer. I am pretty sure that i have correct path. Restart computer, all work


回答 12

就我而言,当我将chromedriver文件复制到c:\ Windows文件夹时,此错误消失了。这是因为Windows目录位于python脚本检查chromedriver可用性的路径中。

In my case, this error disappears when I have copied chromedriver file to c:\Windows folder. Its because windows directory is in the path which python script check for chromedriver availability.


回答 13

如果使用远程解释器,则还必须检查是否定义了其可执行文件PATH。在我的情况下,从远程Docker解释器切换到本地解释器解决了问题。

If you are using remote interpreter you have to also check if its executable PATH is defined. In my case switching from remote Docker interpreter to local interpreter solved the problem.


回答 14

我遇到了与您相同的问题。我正在使用PyCharm编写程序,我认为问题出在PyCharm中而不是OS中。我解决了该问题,方法是进行脚本配置,然后手动编辑环境变量中的PATH。希望对您有所帮助!

I encountered the same problem as yours. I’m using PyCharm to write programs, and I think the problem lies in environment setup in PyCharm rather than the OS. I solved the problem by going to script configuration and then editing the PATH in environment variables manually. Hope you find this helpful!


回答 15

C:\ Windows处添加webdriver(chromedriver.exe或geckodriver.exe)。这对我来说很有效

Add the webdriver(chromedriver.exe or geckodriver.exe) here C:\Windows. This worked in my case


回答 16

最好的方法可能是获取当前目录并将剩余地址附加到该目录。像这样的代码(Windows上的Word。在Linux上,您可以使用pwd行): webdriveraddress = str(os.popen("cd").read().replace("\n", ''))+'\path\to\webdriver'

The best way is maybe to get the current directory and append the remaining address to it. Like this code(Word on windows. On linux you can use something line pwd): webdriveraddress = str(os.popen("cd").read().replace("\n", ''))+'\path\to\webdriver'


回答 17

当我下载chromedriver.exe时,我只是将其移动到PATH文件夹C:\ Windows \ System32 \ chromedriver.exe中,却遇到了完全相同的问题。

对我来说,解决方案是只更改PATH中的文件夹,因此我将其移到了PATH中也位于Pycharm Community bin文件夹中。例如:

  • C:\ Windows \ System32 \ chromedriver.exe->给我exceptions
  • C:\ Program Files \ JetBrains \ PyCharm Community Edition 2019.1.3 \ bin \ chromedriver.exe->运行正常

When I downloaded chromedriver.exe I just move it in PATH folder C:\Windows\System32\chromedriver.exe and had exact same problem.

For me solution was to just change folder in PATH, so I just moved it at Pycharm Community bin folder that was also in PATH. ex:

  • C:\Windows\System32\chromedriver.exe –> Gave me exception
  • C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\bin\chromedriver.exe –> worked fine

回答 18

Mac Mojave运行机器人测试框架和Chrome 77时出现了此问题。这解决了问题。感谢@Navarasu将我指向正确的轨道。

$ pip install webdriver-manager --user # install webdriver-manager lib for python
$ python # open python prompt

接下来,在python提示符下:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())

# ctrl+d to exit

这导致以下错误:

Checking for mac64 chromedriver:xx.x.xxxx.xx in cache
There is no cached driver. Downloading new one...
Trying to download new driver from http://chromedriver.storage.googleapis.com/xx.x.xxxx.xx/chromedriver_mac64.zip
...
TypeError: makedirs() got an unexpected keyword argument 'exist_ok'
  • 我现在得到了最新的下载链接
    • 将chromedriver下载并解压缩到所需位置
    • 例如: ~/chromedriver/chromedriver

~/.bash_profile用编辑器打开并添加:

export PATH="$HOME/chromedriver:$PATH"

打开新的终端窗口,ta-da🎉

Had this issue with Mac Mojave running Robot test framework and Chrome 77. This solved the problem. Kudos @Navarasu for pointing me to the right track.

$ pip install webdriver-manager --user # install webdriver-manager lib for python
$ python # open python prompt

Next, in python prompt:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())

# ctrl+d to exit

This leads to the following error:

Checking for mac64 chromedriver:xx.x.xxxx.xx in cache
There is no cached driver. Downloading new one...
Trying to download new driver from http://chromedriver.storage.googleapis.com/xx.x.xxxx.xx/chromedriver_mac64.zip
...
TypeError: makedirs() got an unexpected keyword argument 'exist_ok'
  • I now got the newest download link
    • Download and unzip chromedriver to where you want
    • For example: ~/chromedriver/chromedriver

Open ~/.bash_profile with editor and add:

export PATH="$HOME/chromedriver:$PATH"

Open new terminal window, ta-da 🎉


回答 19

我在Webdriver 3.8.0(Chrome 73.0.3683.103和ChromeDriver 73.0.3683.68)上遇到了此问题。我做完之后问题就消失了

pip install -U selenium

将Webdriver升级到3.14.1。

I had this problem on Webdriver 3.8.0 (Chrome 73.0.3683.103 and ChromeDriver 73.0.3683.68). The problem disappeared after I did

pip install -U selenium

to upgrade Webdriver to 3.14.1.


回答 20

最好的确定方法是在这里:

下载并解压缩chromedriver并将chromedriver.exe放入C:\ Python27 \ Scripts中,然后您无需提供驱动程序的路径,只需

driver= webdriver.Chrome()

您无需添加路径或其他任何操作

Best way for sure is here:

Download and unzip chromedriver and put ‘chromedriver.exe’ in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

You are done no need to add paths or anything


回答 21

检查您的Chrome驱动程序的路径,它可能无法从那里获取。只需复制即可将驱动程序位置粘贴到代码中。

Check the path of your chrome driver, it might not get it from there. Simply Copy paste the driver location into the code.


回答 22

(对于Mac用户)我有同样的问题,但是我通过以下简单方法解决了:您必须将chromedriver.exe放在执行脚本的同一文件夹中,然后在pyhton中编写以下指令:

导入操作系统

os.environ [“ PATH”] + = os.pathsep + r’X:/您的/文件夹/脚本/’

(for Mac users) I have the same problem but i solved by this simple way: You have to put your chromedriver.exe in the same folder to your executed script and than in pyhton write this instruction :

import os

os.environ[“PATH”] += os.pathsep + r’X:/your/folder/script/’


如何在python中使用Selenium Webdriver滚动网页?

问题:如何在python中使用Selenium Webdriver滚动网页?

我目前正在使用Selenium Webdriver通过Facebook用户朋友页面进行解析,并从AJAX脚本中提取所有ID。但是我需要向下滚动才能得到所有的朋友。如何在Selenium中向下滚动。我正在使用python。

I am currently using selenium webdriver to parse through facebook user friends page and extract all ids from the AJAX script. But I need to scroll down to get all the friends. How can I scroll down in Selenium. I am using python.


回答 0

您可以使用

driver.execute_script("window.scrollTo(0, Y)") 

其中Y是高度(在全高清显示器上为1080)。(感谢@lukeis)

您也可以使用

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

滚动到页面底部。

如果您想滚动到无限加载的页面,例如社交网络页面,facebook等(感谢@Cuong Tran)

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

另一种方法(感谢Juanse)是,选择一个对象,然后

label.sendKeys(Keys.PAGE_DOWN);

You can use

driver.execute_script("window.scrollTo(0, Y)") 

where Y is the height (on a fullhd monitor it’s 1080). (Thanks to @lukeis)

You can also use

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

to scroll to the bottom of the page.

If you want to scroll to a page with infinite loading, like social network ones, facebook etc. (thanks to @Cuong Tran)

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

another method (thanks to Juanse) is, select an object and

label.sendKeys(Keys.PAGE_DOWN);

回答 1

如果要向下滚动到无限页面的底部(例如linkedin.com),可以使用以下代码:

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

参考:https : //stackoverflow.com/a/28928684/1316860

If you want to scroll down to bottom of infinite page (like linkedin.com), you can use this code:

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

Reference: https://stackoverflow.com/a/28928684/1316860


回答 2

您可以send_keys用来模拟END(或PAGE_DOWN)按键(通常会滚动页面):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)

You can use send_keys to simulate an END (or PAGE_DOWN) key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)

回答 3

如图相同的方法在这里

在python中,您可以使用

driver.execute_script("window.scrollTo(0, Y)")

(Y是您要滚动到的垂直位置)

same method as shown here:

in python you can just use

driver.execute_script("window.scrollTo(0, Y)")

(Y is the vertical position you want to scroll to)


回答 4

element=find_element_by_xpath("xpath of the li you are trying to access")

element.location_once_scrolled_into_view

当我尝试访问不可见的“ li”时,这很有帮助。

element=find_element_by_xpath("xpath of the li you are trying to access")

element.location_once_scrolled_into_view

this helped when I was trying to access a ‘li’ that was not visible.


回答 5

出于我的目的,我想向下滚动更多,同时牢记窗口的位置。我的解决方案是相似的,并使用window.scrollY

driver.execute_script("window.scrollTo(0, window.scrollY + 200)")

它将转到当前的y滚动位置+ 200

For my purpose, I wanted to scroll down more, keeping the windows position in mind. My solution was similar and used window.scrollY

driver.execute_script("window.scrollTo(0, window.scrollY + 200)")

which will go to the current y scroll position + 200


回答 6

这是您向下滚动网页的方式:

driver.execute_script("window.scrollTo(0, 1000);")

This is how you scroll down the webpage:

driver.execute_script("window.scrollTo(0, 1000);")

回答 7

我发现解决该问题的最简单方法是选择一个标签,然后发送:

label.sendKeys(Keys.PAGE_DOWN);

希望它能起作用!

The easiest way i found to solve that problem was to select a label and then send:

label.sendKeys(Keys.PAGE_DOWN);

Hope it works!


回答 8

这些答案都不适合我,至少不是向下滚动Facebook搜索结果页面有效,但经过大量测试,我发现此解决方案:

while driver.find_element_by_tag_name('div'):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    Divs=driver.find_element_by_tag_name('div').text
    if 'End of Results' in Divs:
        print 'end'
        break
    else:
        continue

None of these answers worked for me, at least not for scrolling down a facebook search result page, but I found after a lot of testing this solution:

while driver.find_element_by_tag_name('div'):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    Divs=driver.find_element_by_tag_name('div').text
    if 'End of Results' in Divs:
        print 'end'
        break
    else:
        continue

回答 9

使用youtube时,浮动元素的滚动高度为“ 0”,因此请不要使用“ return document.body.scrollHeight”,而是尝试使用此“ return document.documentElement.scrollHeight” ,根据您的互联网调整滚动暂停时间速度,否则它将只运行一次,然后在此之后中断。

SCROLL_PAUSE_TIME = 1

# Get scroll height
"""last_height = driver.execute_script("return document.body.scrollHeight")

this dowsnt work due to floating web elements on youtube
"""

last_height = driver.execute_script("return document.documentElement.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.documentElement.scrollHeight")
    if new_height == last_height:
       print("break")
       break
    last_height = new_height

When working with youtube the floating elements give the value “0” as the scroll height so rather than using “return document.body.scrollHeight” try using this one “return document.documentElement.scrollHeight” adjust the scroll pause time as per your internet speed else it will run for only one time and then breaks after that.

SCROLL_PAUSE_TIME = 1

# Get scroll height
"""last_height = driver.execute_script("return document.body.scrollHeight")

this dowsnt work due to floating web elements on youtube
"""

last_height = driver.execute_script("return document.documentElement.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.documentElement.scrollHeight")
    if new_height == last_height:
       print("break")
       break
    last_height = new_height

回答 10

我正在寻找一种滚动浏览动态网页的方法,并在到达页面末尾并发现该线程时自动停止。

@Cuong Tran的帖子进行了主要修改,是我正在寻找的答案。我认为其他人可能会发现此修改很有用(它对代码的工作方式有明显影响),因此,本文发布了。

修改是移动捕获循环最后一页高度的语句(以便使每项检查都与上一页高度进行比较)。

因此,下面的代码:

连续向下滚动动态网页(.scrollTo()),仅在一次迭代中页面高度保持不变时停止。

(还有另一种修改,其中break语句位于另一个可以删除的条件内(如果页面为“ sticks”)。

    SCROLL_PAUSE_TIME = 0.5


    while True:

        # Get scroll height
        ### This is the difference. Moving this *inside* the loop
        ### means that it checks if scrollTo is still scrolling 
        last_height = driver.execute_script("return document.body.scrollHeight")

        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:

            # try again (can be removed)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

            # Wait to load page
            time.sleep(SCROLL_PAUSE_TIME)

            # Calculate new scroll height and compare with last scroll height
            new_height = driver.execute_script("return document.body.scrollHeight")

            # check if the page height has remained the same
            if new_height == last_height:
                # if so, you are done
                break
            # if not, move on to the next loop
            else:
                last_height = new_height
                continue

I was looking for a way of scrolling through a dynamic webpage, and automatically stopping once the end of the page is reached, and found this thread.

The post by @Cuong Tran, with one main modification, was the answer that I was looking for. I thought that others might find the modification helpful (it has a pronounced effect on how the code works), hence this post.

The modification is to move the statement that captures the last page height inside the loop (so that each check is comparing to the previous page height).

So, the code below:

Continuously scrolls down a dynamic webpage (.scrollTo()), only stopping when, for one iteration, the page height stays the same.

(There is another modification, where the break statement is inside another condition (in case the page ‘sticks’) which can be removed).

    SCROLL_PAUSE_TIME = 0.5


    while True:

        # Get scroll height
        ### This is the difference. Moving this *inside* the loop
        ### means that it checks if scrollTo is still scrolling 
        last_height = driver.execute_script("return document.body.scrollHeight")

        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:

            # try again (can be removed)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

            # Wait to load page
            time.sleep(SCROLL_PAUSE_TIME)

            # Calculate new scroll height and compare with last scroll height
            new_height = driver.execute_script("return document.body.scrollHeight")

            # check if the page height has remained the same
            if new_height == last_height:
                # if so, you are done
                break
            # if not, move on to the next loop
            else:
                last_height = new_height
                continue

回答 11

该代码滚动到底部,但不需要您每次都等待。它会不断滚动,然后在底部停止(或超时)

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://example.com')

pre_scroll_height = driver.execute_script('return document.body.scrollHeight;')
run_time, max_run_time = 0, 1
while True:
    iteration_start = time.time()
    # Scroll webpage, the 100 allows for a more 'aggressive' scroll
    driver.execute_script('window.scrollTo(0, 100*document.body.scrollHeight);')

    post_scroll_height = driver.execute_script('return document.body.scrollHeight;')

    scrolled = post_scroll_height != pre_scroll_height
    timed_out = run_time >= max_run_time

    if scrolled:
        run_time = 0
        pre_scroll_height = post_scroll_height
    elif not scrolled and not timed_out:
        run_time += time.time() - iteration_start
    elif not scrolled and timed_out:
        break

# closing the driver is optional 
driver.close()

这比每次等待0.5-3秒等待响应要快得多,因为该响应可能需要0.1秒

This code scrolls to the bottom but doesn’t require that you wait each time. It’ll continually scroll, and then stop at the bottom (or timeout)

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://example.com')

pre_scroll_height = driver.execute_script('return document.body.scrollHeight;')
run_time, max_run_time = 0, 1
while True:
    iteration_start = time.time()
    # Scroll webpage, the 100 allows for a more 'aggressive' scroll
    driver.execute_script('window.scrollTo(0, 100*document.body.scrollHeight);')

    post_scroll_height = driver.execute_script('return document.body.scrollHeight;')

    scrolled = post_scroll_height != pre_scroll_height
    timed_out = run_time >= max_run_time

    if scrolled:
        run_time = 0
        pre_scroll_height = post_scroll_height
    elif not scrolled and not timed_out:
        run_time += time.time() - iteration_start
    elif not scrolled and timed_out:
        break

# closing the driver is optional 
driver.close()

This is much faster than waiting 0.5-3 seconds each time for a response, when that response could take 0.1 seconds


回答 12

滚动加载页面。示例:中,定额等

last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight-1000);")
        # Wait to load the page.
        driver.implicitly_wait(30) # seconds
        new_height = driver.execute_script("return document.body.scrollHeight")
    
        if new_height == last_height:
            break
        last_height = new_height
        # sleep for 30s
        driver.implicitly_wait(30) # seconds
    driver.quit()

scroll loading pages. Example: medium, quora,etc

last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight-1000);")
        # Wait to load the page.
        driver.implicitly_wait(30) # seconds
        new_height = driver.execute_script("return document.body.scrollHeight")
    
        if new_height == last_height:
            break
        last_height = new_height
        # sleep for 30s
        driver.implicitly_wait(30) # seconds
    driver.quit()

回答 13

如果要在特定视图/框架(WebElement)中滚动,则只需将“ body”替换为要在其中滚动的特定元素。我在下面的示例中通过“ getElementById”获得该元素:

self.driver.execute_script('window.scrollTo(0, document.getElementById("page-manager").scrollHeight);')

例如,在YouTube上就是这种情况。

if you want to scroll within a particular view/frame (WebElement), what you only need to do is to replace “body” with a particular element that you intend to scroll within. i get that element via “getElementById” in the example below:

self.driver.execute_script('window.scrollTo(0, document.getElementById("page-manager").scrollHeight);')

this is the case on YouTube, for example…


回答 14

ScrollTo()功能不再起作用。这是我使用的,效果很好。

driver.execute_script("document.getElementById('mydiv').scrollIntoView();")

The ScrollTo() function doesn’t work anymore. This is what I used and it worked fine.

driver.execute_script("document.getElementById('mydiv').scrollIntoView();")

回答 15

driver.execute_script("document.getElementById('your ID Element').scrollIntoView();")

它适合我的情况。

driver.execute_script("document.getElementById('your ID Element').scrollIntoView();")

it’s working for my case.


WebDriver click()与JavaScript click()

问题:WebDriver click()与JavaScript click()

故事:

在StackOverflow上,我看到用户报告他们无法通过selenium WebDriver“单击”命令单击元素,并且可以通过执行脚本来解决JavaScript单击问题。

Python中的示例:

element = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].click();", element)

WebDriverJS /量角器中的示例:

var elm = $("#myid");
browser.executeScript("arguments[0].click();", elm.getWebElement());

问题:

为什么在常规WebDriver单击不起作用时单击“通过JavaScript”有效?这到底是什么时候发生的,这种解决方法(如果有)的缺点是什么?

我个人使用此变通办法时并未完全理解为什么必须这样做以及它可能导致什么问题。

The Story:

Here on StackOverflow, I’ve seen users reporting that they cannot click an element via selenium WebDriver “click” command and can work around it with a JavaScript click by executing a script.

Example in Python:

element = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].click();", element)

Example in WebDriverJS/Protractor:

var elm = $("#myid");
browser.executeScript("arguments[0].click();", elm.getWebElement());

The Question:

Why is clicking “via JavaScript” works when a regular WebDriver click does not? When exactly is this happening and what is the downside of this workaround (if any)?

I personally used this workaround without fully understanding why I have to do it and what problems it can lead to.


回答 0

当前接受的答案所暗示的相反,关于PhantomJS并没有特定于WebDriver单击和使用JavaScript的区别。

区别

两种方法之间的本质区别是所有浏览器都共有的,可以很简单地解释一下:

  • WebDriver:当WebDriver进行单击时,它会尽可能地尝试模拟真实用户使用浏览器时发生的情况。假设您有一个元素A,它是一个表示“单击我”的按钮,一个元素B是一个div透明的元素,但具有其尺寸和zIndex设置,使其完全覆盖A。然后,您告诉WebDriver单击A。WebDriver将模拟点击,使B 首先获得点击。为什么?因为B涵盖了A,并且如果用户尝试单击A,则B将首先获得该事件。A是否最终会获得click事件取决于B如何处理该事件。无论如何,在这种情况下,WebDriver的行为与真实用户尝试单击A时的行为相同。

  • JavaScript:现在,假设您使用JavaScript来做A.click()这种单击方法不能重现用户尝试单击A时实际发生的情况。JavaScript将click事件直接发送给A,而B将不会获得任何事件。

为什么在WebDriver单击不起作用时JavaScript单击有效?

正如我上面提到的,WebDriver会尽可能地模拟真实用户使用浏览器时发生的情况。事实是,DOM可以包含用户无法与之交互的元素,并且WebDriver不允许您单击这些元素。除了我提到的重叠情况之外,这还意味着无法单击不可见元素。我在“堆栈溢出”问题中看到的一个常见案例是某人试图与DOM中已经存在的GUI元素进行交互,但只有在处理了其他某些元素后才可见。有时在下拉菜单中会发生这种情况:您必须先单击按钮,然后弹出菜单,然后才能选择菜单项。如果有人尝试在菜单可见之前单击菜单项,如果此人随后尝试使用JavaScript进行操作,那么它将起作用,因为事件是直接传递给元素的,而与可见性无关。

什么时候应该使用JavaScript进行点击?

如果您使用Selenium来测试应用程序,那么我对这个问题的回答是“几乎不会”。总的来说,您的Selenium测试应该重现用户对浏览器的操作。以下拉菜单为例:测试应单击首先显示下拉菜单的按钮,然后单击菜单项。如果由于按钮不可见而导致GUI出现问题,或者按钮无法显示菜单项或类似内容,则测试将失败并且您将检测到该错误。如果使用JavaScript单击鼠标,则将无法通过自动测试检测到这些错误。

我说“几乎从不”是因为使用JavaScript可能会有exceptions。但是,它们应该很少见。

如果您使用Selenium 抓取站点,则尝试重现用户行为并不那么重要。因此,使用JavaScript绕过GUI并不是什么大问题。

Contrarily to what the currently accepted answer suggests, there’s nothing specific to PhantomJS when it comes to the difference between having WebDriver do a click and doing it in JavaScript.

The Difference

The essential difference between the two methods is common to all browsers and can be explained pretty simply:

  • WebDriver: When WebDriver does the click, it attempts as best as it can to simulate what happens when a real user uses the browser. Suppose you have an element A which is a button that says “Click me” and an element B which is a div element which is transparent but has its dimensions and zIndex set so that it completely covers A. Then you tell WebDriver to click A. WebDriver will simulate the click so that B receives the click first. Why? Because B covers A, and if a user were to try to click on A, then B would get the event first. Whether or not A would eventually get the click event depends on how B handles the event. At any rate, the behavior with WebDriver in this case is the same as when a real user tries to click on A.

  • JavaScript: Now, suppose you use JavaScript to do A.click(). This method of clicking does not reproduce what really happens when the user tries to click A. JavaScript sends the click event directly to A, and B will not get any event.

Why a JavaScript Click Works When a WebDriver Click Does Not?

As I mentioned above WebDriver will try to simulate as best it can what happens when a real user is using a browser. The fact of the matter is that the DOM can contain elements that a user cannot interact with, and WebDriver won’t allow you to click on these element. Besides the overlapping case I mentioned, this also entails that invisible elements cannot be clicked. A common case I see in Stack Overflow questions is someone who is trying to interact with a GUI element that already exists in the DOM but becomes visible only when some other element has been manipulated. This sometimes happens with dropdown menus: you have to first click on the button the brings up the dropdown before a menu item can be selected. If someone tries to click the menu item before the menu is visible, WebDriver will balk and say that the element cannot be manipulated. If the person then tries to do it with JavaScript, it will work because the event is delivered directly to the element, irrespective of visibility.

When Should You Use JavaScript for Clicking?

If you are using Selenium for testing an application, my answer to this question is “almost never”. By and large, your Selenium test should reproduce what a user would do with the browser. Taking the example of the drop down menu: a test should click on the button that brings up the drop down first, and then click on the menu item. If there is a problem with the GUI because the button is invisible, or the button fails to show the menu items, or something similar, then your test will fail and you’ll have detected the bug. If you use JavaScript to click around, you won’t be able to detect these bugs through automated testing.

I say “almost never” because there may be exceptions where it makes sense to use JavaScript. They should be very rare, though.

If you are using Selenium for scraping sites, then it is not as critical to attempt to reproduce user behavior. So using JavaScript to bypass the GUI is less of an issue.


回答 1

驱动程序执行的单击尝试在JavaScript HTMLElement.click()click事件执行默认操作时,即使元素不可交互,也尽可能模拟真实用户的行为。

不同之处在于:

  • 驱动程序通过将元素滚动到视图中来确保该元素可见,并检查该元素是否可交互

    驱动程序将引发错误:

    • 当点击坐标顶部的元素不是目标元素或后代时
    • 当元素没有正尺寸或完全透明时
    • 当元素是禁用的输入或按​​钮(属性/属性disabledtrue)时
    • 当元素的鼠标指针被禁用(CSS pointer-eventsnone)时


    HTMLElement.click()如果元素被禁用, JavaScript 将始终执行默认操作,或者至多只会静默失败。

  • 如果元素是可聚焦的,则希望驾驶员将其聚焦。

    JavaScript HTMLElement.click()不会。

  • 希望驱动程序像真实用户一样发出所有事件(mousemove,mousedown,mouseup,click等)。

    JavaScript HTMLElement.click()仅发出click事件。该页面可能依赖于这些额外的事件,并且如果未发出这些事件,它们的行为可能会有所不同。

    这些是驱动程序发出的单击Chrome的事件:

    mouseover {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    mousemove {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    mousedown {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    mouseup {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    click {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }

    这是JavaScript注入发出的事件:

    click {target:#topic, clientX:0, clientY:0, isTrusted:false, ... }
  • JavaScript发出的事件.click() 不受信任,并且默认操作不能被调用:

    https://developer.mozilla.org/zh/docs/Web/API/Event/isTrusted
    https://googlechrome.github.io/samples/event-istrusted/index.html

    请注意,某些驱动程序仍在生成不受信任的事件。从2.1版开始,PhantomJS就是这种情况。

  • JavaScript发出的事件.click() 没有click的坐标

    属性clientX, clientY, screenX, screenY, layerX, layerY设置为0。该页面可能依赖于它们,并且可能会有所不同。


可以使用JavaScript .click()抓取一些数据,但这不是在测试环境中。由于它无法模拟用户的行为,因此无法达到测试的目的。因此,如果来自驱动程序的单击失败,则实际用户很可能也将在相同条件下无法执行相同的单击。


是什么使驱动程序在我们期望成功时无法单击元素?

  • 由于延迟或过渡效果,目标元素尚不可见/不可交互。

    一些例子 :

    https://developer.mozilla.org/fr/docs/Web(下拉导航菜单) http://materializecss.com/side-nav.html(下拉侧栏)

    工作环境:

    添加服务员以等待可见性,最小尺寸或稳定位置:

    // wait visible
    browser.wait(ExpectedConditions.visibilityOf(elem), 5000);
    
    // wait visible and not disabled
    browser.wait(ExpectedConditions.elementToBeClickable(elem), 5000);
    
    // wait for minimum width
    browser.wait(function minimumWidth() {
        return elem.getSize().then(size => size.width > 50);
    }, 5000);

    重试单击直到成功:

    browser.wait(function clickSuccessful() {
        return elem.click().then(() => true, (ex) => false);
    }, 5000);

    添加与动画/过渡的持续时间匹配的延迟:

    browser.sleep(250);


  • 目标元素最终被浮动元素覆盖一旦滚动到视图中:

    驱动程序自动将元素滚动到视图中以使其可见。如果页面包含浮动/粘滞元素(菜单,广告,页脚,通知,Cookie策略..),则该元素可能最终被覆盖,将不再可见/不可交互。

    示例:https//twitter.com/?lang = zh-CN

    解决方法:

    将窗口的大小设置为较大的大小,以避免滚动或浮动元素。

    Y将鼠标移到具有负偏移量的元素上,然后单击它:

      browser.actions()
         .mouseMove(elem, {x: 0, y: -250})
         .click()
         .perform();

    单击之前,将元素滚动到窗口的中心:

    browser.executeScript(function scrollCenter(elem) {
      var win = elem.ownerDocument.defaultView || window,
        box = elem.getBoundingClientRect(),
        dy = box.top - (win.innerHeight - box.height) / 2;
      win.scrollTo(win.pageXOffset, win.pageYOffset + dy);
    }, element);
    
    element.click();

    如果无法避免,请隐藏浮动元素:

    browser.executeScript(function scrollCenter(elem) {
      elem.style.display = 'none';
    }, element);

The click executed by the driver tries to simulate the behavior of a real user as close as possible while the JavaScript HTMLElement.click() performs the default action for the click event, even if the element is not interactable.

The differences are:

  • The driver ensures that the element is visible by scrolling it into the view and checks that the element is interactable.

    The driver will raise an error:

    • when the element on top at the coordinates of the click is not the targeted element or a descendant
    • when the element doesn’t have a positive size or if it is fully transparent
    • when the element is a disabled input or button (attribute/property disabled is true)
    • when the element has the mouse pointer disabled (CSS pointer-events is none)


    A JavaScript HTMLElement.click() will always perform the default action or will at best silently fail if the element is a disabled.

  • The driver is expected to bring the element into focus if it is focusable.

    A JavaScript HTMLElement.click() won’t.

  • The driver is expected to emit all the events (mousemove, mousedown, mouseup, click, …) just like like a real user.

    A JavaScript HTMLElement.click() emits only the click event. The page might rely on these extra events and might behave differently if they are not emitted.

    These are the events emitted by the driver for a click with Chrome:

    mouseover {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    mousemove {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    mousedown {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    mouseup {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    click {target:#topic, clientX:222, clientY:343, isTrusted:true, ... }
    

    And this is the event emitted with a JavaScript injection:

    click {target:#topic, clientX:0, clientY:0, isTrusted:false, ... }
    
  • The event emitted by a JavaScript .click() is not trusted and the default action may not be invoked:

    https://developer.mozilla.org/en/docs/Web/API/Event/isTrusted
    https://googlechrome.github.io/samples/event-istrusted/index.html

    Note that some of the drivers are still generating untrusted events. This is the case with PhantomJS as of version 2.1.

  • The event emitted by a JavaScript .click() doesn’t have the coordinates of the click.

    The properties clientX, clientY, screenX, screenY, layerX, layerY are set to 0. The page might rely on them and might behave differently.


It may be ok to use a JavaScript .click() to scrap some data, but it is not in a testing context. It defeats the purpose of the test since it doesn’t simulate the behavior of a user. So, if the click from the driver fails, then a real user will most likely also fail to perform the same click in the same conditions.


What makes the driver fail to click an element when we expect it to succeed?

  • The targeted element is not yet visible/interactable due to a delay or a transition effect.

    Some examples :

    https://developer.mozilla.org/fr/docs/Web (dropdown navigation menu) http://materializecss.com/side-nav.html (dropdown side bar)

    Workarrounds:

    Add a waiter to wait for the visibility, a minimum size or a steady position :

    // wait visible
    browser.wait(ExpectedConditions.visibilityOf(elem), 5000);
    
    // wait visible and not disabled
    browser.wait(ExpectedConditions.elementToBeClickable(elem), 5000);
    
    // wait for minimum width
    browser.wait(function minimumWidth() {
        return elem.getSize().then(size => size.width > 50);
    }, 5000);
    

    Retry to click until it succeeds :

    browser.wait(function clickSuccessful() {
        return elem.click().then(() => true, (ex) => false);
    }, 5000);
    

    Add a delay matching the duration of the animation/transition :

    browser.sleep(250);
    


  • The targeted element ends-up covered by a floating element once scrolled into the view:

    The driver automatically scrolls the element into the view to make it visible. If the page contains a floating/sticky element (menu, ads, footer, notification, cookie policy..), the element may end-up covered and will no longer be visible/interactable.

    Example: https://twitter.com/?lang=en

    Workarounds:

    Set the size of the window to a larger one to avoid the scrolling or the floating element.

    Mover over the element with a negative Y offset and then click it:

      browser.actions()
         .mouseMove(elem, {x: 0, y: -250})
         .click()
         .perform();
    

    Scroll the element to the center of the window before the click:

    browser.executeScript(function scrollCenter(elem) {
      var win = elem.ownerDocument.defaultView || window,
        box = elem.getBoundingClientRect(),
        dy = box.top - (win.innerHeight - box.height) / 2;
      win.scrollTo(win.pageXOffset, win.pageYOffset + dy);
    }, element);
    
    element.click();
    

    Hide the floating element if it can’t be avoided:

    browser.executeScript(function scrollCenter(elem) {
      elem.style.display = 'none';
    }, element);
    

回答 2

注意:我们将“点击”称为最终用户点击。“ js click”是通过JS点击的

为什么在常规WebDriver单击不起作用时单击“通过JavaScript”有效?

有两种情况会发生这种情况:

I. 如果您正在使用PhamtomJS

这是的最常见的已知行为PhantomJS。例如,某些元素有时不可单击<div>。这是因为PhantomJS最初是用来模拟浏览器引擎的(例如初始HTML + CSS->计算CSS->呈现)。但这并不意味着要以最终用户的方式进行交互(查看,单击,拖动)。因此PhamtomJS,最终用户交互仅部分支持。

JS为什么点击工作?至于任一点击,它们都是平均点击。它就像带有1个枪管2个扳机的枪。视口中的一个,JS中的一个。由于可以PhamtomJS很好地模拟浏览器的引擎,因此JS单击应该可以很好地工作。

二。“ click”的事件处理程序必须在糟糕的时间内绑定。

例如,我们得到了一个 <div>

  • ->我们做一些计算

  • ->然后将click事件绑定到<div>

  • ->加上一些错误的角度编码(例如,不能正确处理示波器的周期)

我们可能最终得到相同的结果。单击将不起作用,因为WebdriverJS在没有单击事件处理程序的情况下会尝试单击该元素。

JS为什么点击工作?JS单击就像将JS直接注入浏览器。可能有2种方式,

拳头是通过devtools控制台(是的,WebdriverJS确实与devtools的控制台进行通信)。

其次是将<script>标记直接注入HTML。

对于每个浏览器,其行为将有所不同。但是无论如何,这些方法比单击按钮更复杂。Click正在使用已经存在的内容(最终用户单击),js click正在通过后门。

对于js,单击将显示为异步任务。这与一个复杂的主题“ 浏览器异步任务和CPU任务调度 ”相关(一会儿再读也找不到文章)。简而言之,这主要是因为js click需要等待CPU任务调度周期,并且在click事件绑定后运行速度会变慢。 (当您发现元素有时可单击,有时却不可单击时,您可能会知道这种情况。)

这到底是什么时候发生的,这种解决方法(如果有)的缺点是什么?

=>如上所述,两者都意味着一个目的,但是关于使用哪个入口:

  • 点击:使用默认情况下提供的浏览器。
  • JS click:正在通过后门。

=>对于性能,很难说,因为它依赖于浏览器。但通常:

  • 单击:并不意味着更快,而只是在CPU执行任务的计划列表中签名更高的位置。
  • JS单击:并不意味着速度较慢,而仅是它登录到CPU任务计划列表的最后位置。

=>缺点:

  • 点击:除了您使用PhamtomJS之外,似乎没有其他缺点。
  • JS单击:对健康非常不利。您可能不小心单击了视图中没有的内容。使用此功能时,请确保该元素在那里并且可供查看,然后单击以作为最终用户的观点。

PS,如果您正在寻找解决方案。

  • 使用PhantomJS?我建议改用无头的Chrome。是的,您可以在Ubuntu上无头设置Chrome。事物的运行方式与Chrome一样,但它没有视图,并且像PhantomJS一样没有虫子。
  • 不使用PhamtomJS但仍然有问题吗?我建议使用带有browser.wait()(分度器的ExpectedCondition)(检查此以获得更多信息

(我想简短一点,但结局很糟。与理论有关的任何事情都难以解释…)

NOTE: let’s call ‘click’ is end-user click. ‘js click’ is click via JS

Why is clicking “via JavaScript” works when a regular WebDriver click does not?

There are 2 cases for this to happen:

I. If you are using PhamtomJS

Then this is the most common known behavior of PhantomJS . Some elements are sometimes not clickable, for example <div>. This is because PhantomJS was original made for simulating the engine of browsers (like initial HTML + CSS -> computing CSS -> rendering). But it does not mean to be interacted with as an end user’s way (viewing, clicking, dragging). Therefore PhamtomJS is only partially supported with end-users interaction.

WHY DOES JS CLICK WORK? As for either click, they are all mean click. It is like a gun with 1 barrel and 2 triggers. One from the viewport, one from JS. Since PhamtomJS great in simulating browser’s engine, a JS click should work perfectly.

II. The event handler of “click” got to bind in the bad period of time.

For example, we got a <div>

  • -> We do some calculation

  • -> then we bind event of click to the <div>.

  • -> Plus with some bad coding of angular (e.g. not handling scope’s cycle properly)

We may end up with the same result. Click won’t work, because WebdriverJS trying to click on the element when it has no click event handler.

WHY DOES JS CLICK WORK? Js click is like injecting js directly into the browser. Possible with 2 ways,

Fist is through devtools console (yes, WebdriverJS does communicate with devtools’ console).

Second is inject a <script> tag directly into HTML.

For each browser, the behavior will be different. But regardless, these methods are more complicating than clicking on the button. Click is using what already there (end-users click), js click is going through backdoor.

And for js click will appear to be an asynchronous task. This is related a with a kinda complex topic of ‘browser asynchronous task and CPU task scheduling‘ (read it a while back can’t find the article again). For short this will mostly result as js click will need to wait for a cycle of task scheduling of CPU and it will be ran a bit slower after the binding of the click event. (You could know this case when you found the element sometimes clickable, sometimes not. )

When exactly is this happening and what is the downside of this workaround (if any)?

=> As mention above, both mean for one purpose, but about using which entrance:

  • Click: is using what providing by default of browser.
  • JS click: is going through backdoor.

=> For performance, it is hard to say because it relies on browsers. But generally:

  • Click: doesn’t mean faster but only signed higher position in schedule list of CPU execution task.
  • JS click: doesn’t mean slower but only it signed into the last position of schedule list of CPU task.

=> Downsides:

  • Click: doesn’t seem to have any downside except you are using PhamtomJS.
  • JS click: very bad for health. You may accidentally click on something that doesn’t there on the view. When you use this, make sure the element is there and available to view and click as the point of view of end-user.

P.S. if you are looking for a solution.

  • Using PhantomJS? I will suggest using Chrome headless instead. Yes, you can set up Chrome headless on Ubuntu. Thing runs just like Chrome but it only does not have a view and less buggy like PhantomJS.
  • Not using PhamtomJS but still having problems? I will suggest using ExpectedCondition of Protractor with browser.wait() (check this for more information)

(I want to make it short, but ended up badly. Anything related with theory is complicated to explain…)


如何使用python在Selenium中以编程方式使Firefox无头?

问题:如何使用python在Selenium中以编程方式使Firefox无头?

我正在使用python,selenium和firefox运行此代码,但仍获得firefox的“ head”版本:

binary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', log_file=sys.stdout)
binary.add_command_line_options('-headless')
self.driver = webdriver.Firefox(firefox_binary=binary)

我还尝试了一些二进制的变体:

binary = FirefoxBinary('C:\\Program Files\\Nightly\\firefox.exe', log_file=sys.stdout)
        binary.add_command_line_options("--headless")

I am running this code with python, selenium, and firefox but still get ‘head’ version of firefox:

binary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', log_file=sys.stdout)
binary.add_command_line_options('-headless')
self.driver = webdriver.Firefox(firefox_binary=binary)

I also tried some variations of binary:

binary = FirefoxBinary('C:\\Program Files\\Nightly\\firefox.exe', log_file=sys.stdout)
        binary.add_command_line_options("--headless")

回答 0

要不费吹灰之力地调用Firefox浏览器,可以headless通过以下Options()类设置属性:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()

还有另一种方法可以完成无头模式。如果你需要禁用或启用Firefox中的无头模式,而无需修改代码,您可以设置环境变量MOZ_HEADLESS,以什么,如果你想Firefox的运行无头,或根本不设置它。

例如,在使用持续集成并且希望在服务器中运行功能测试但仍能够在PC上以正常模式运行测试时,此功能非常有用。

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

要么

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode

奥托罗

如何配置ChromeDriver通过Selenium以无头模式启动Chrome浏览器?

To invoke Firefox Browser headlessly, you can set the headless property through Options() class as follows:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()

There’s another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS to whatever if you want Firefox to run headless, or don’t set it at all.

This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

or

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode

Outro

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?


回答 1

第一个答案不再起作用。

这对我有用:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

The first answer does’t work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

回答 2

我的答案:

set_headless(headless=True) is deprecated. 

https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.options.html

options.headless = True

为我工作

My answer:

set_headless(headless=True) is deprecated. 

https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.options.html

options.headless = True

works for me


回答 3

只是为以后可能会发现此问题的人提供的注释(并希望使用java的方法来实现此目的);FirefoxOptions还能够启用无头模式:

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);

Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions is also capable of enabling the headless mode:

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);

回答 4

Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:

// Can pass browser type 

if brower.lower() == 'chrome':
    driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
    ch_Options = Options()
    ch_Options.add_argument('--headless')
    ch_Options.add_argument("--disable-gpu")
    driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
    ff_option = FFOption()
    ff_option.add_argument('--headless')
    ff_option.add_argument("--disable-gpu")
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
    driver = webdriver.Ie('..\drivers\IEDriverServer')
else:
    raise Exception('Invalid Browser Type')
Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:

// Can pass browser type 

if brower.lower() == 'chrome':
    driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
    ch_Options = Options()
    ch_Options.add_argument('--headless')
    ch_Options.add_argument("--disable-gpu")
    driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
    ff_option = FFOption()
    ff_option.add_argument('--headless')
    ff_option.add_argument("--disable-gpu")
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
    driver = webdriver.Ie('..\drivers\IEDriverServer')
else:
    raise Exception('Invalid Browser Type')

Python Selenium访问HTML源

问题:Python Selenium访问HTML源

如何使用Selenium模块和Python在变量中获取HTML源代码?

我想做这样的事情:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://example.com")
if "whatever" in html_source:
    # Do something
else:
    # Do something else

我怎样才能做到这一点?我不知道如何访问HTML源。

How can I get the HTML source in a variable using the Selenium module with Python?

I wanted to do something like this:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://example.com")
if "whatever" in html_source:
    # Do something
else:
    # Do something else

How can I do this? I don’t know how to access the HTML source.


回答 0

您需要访问page_source属性:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://example.com")

html_source = browser.page_source
if "whatever" in html_source:
    # do something
else:
    # do something else

You need to access the page_source property:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://example.com")

html_source = browser.page_source
if "whatever" in html_source:
    # do something
else:
    # do something else

回答 1

借助Selenium2Library,您可以使用 get_source()

import Selenium2Library
s = Selenium2Library.Selenium2Library()
s.open_browser("localhost:7080", "firefox")
source = s.get_source()

With Selenium2Library you can use get_source()

import Selenium2Library
s = Selenium2Library.Selenium2Library()
s.open_browser("localhost:7080", "firefox")
source = s.get_source()

回答 2

driver.page_source将帮助您获取页面源代码。您可以检查页面源中是否存在文本。

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("some url")
if "your text here" in driver.page_source:
    print('Found it!')
else:
    print('Did not find it.')

如果要将页面源存储在变量中,请在driver.get之后添加以下行:

var_pgsource=driver.page_source

并将if条件更改为:

if "your text here" in var_pgsource:

driver.page_source will help you get the page source code. You can check if the text is present in the page source or not.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("some url")
if "your text here" in driver.page_source:
    print('Found it!')
else:
    print('Did not find it.')

If you want to store the page source in a variable, add below line after driver.get:

var_pgsource=driver.page_source

and change the if condition to:

if "your text here" in var_pgsource:

回答 3

通过使用页面源,您将获得完整的HTML代码。
因此,首先确定需要检索数据或单击元素的代码或标记块。

options = driver.find_elements_by_name_("XXX")
for option in options:
    if option.text == "XXXXXX":
        print(option.text)
        option.click()

您可以按名称,XPath,ID,链接和CSS路径找到元素。

By using the page source you will get the whole HTML code.
So first decide the block of code or tag in which you require to retrieve the data or to click the element..

options = driver.find_elements_by_name_("XXX")
for option in options:
    if option.text == "XXXXXX":
        print(option.text)
        option.click()

You can find the elements by name, XPath, id, link and CSS path.


回答 4

要回答有关获取用于urllib 的URL的问题,只需执行以下JavaScript代码:

url = browser.execute_script("return window.location;")

To answer your question about getting the URL to use for urllib, just execute this JavaScript code:

url = browser.execute_script("return window.location;")

回答 5

您可以简单地使用该WebDriver对象,并通过其@property字段访问页面源代码page_source

试试这个代码片段:-)

from selenium import webdriver
driver = webdriver.Firefox('path/to/executable')
driver.get('https://some-domain.com')
source = driver.page_source
if 'stuff' in source:
    print('found...')
else:
    print('not in source...')

You can simply use the WebDriver object, and access to the page source code via its @property field page_source

Try this code snippet :-)

from selenium import webdriver
driver = webdriver.Firefox('path/to/executable')
driver.get('https://some-domain.com')
source = driver.page_source
if 'stuff' in source:
    print('found...')
else:
    print('not in source...')

回答 6

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

现在您可以应用BeautifulSoup函数来提取数据…

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

Now you can apply BeautifulSoup function to extract data…


回答 7

我建议使用urllib获取源代码,如果要解析,请使用Beautiful Soup之类的东西。

import urllib

url = urllib.urlopen("http://example.com") # Open the URL.
content = url.readlines() # Read the source and save it to a variable.

I’d recommend getting the source with urllib and, if you’re going to parse, use something like Beautiful Soup.

import urllib

url = urllib.urlopen("http://example.com") # Open the URL.
content = url.readlines() # Read the source and save it to a variable.

Selenium:FirefoxProfile异常无法加载配置文件

问题:Selenium:FirefoxProfile异常无法加载配置文件

对于这个先前的问题,我将Selenium更新到了2.0.1版本,但是现在我又遇到了另一个错误,即使配置文件位于以下位置/tmp/webdriver-py-profilecopy

  在执行中,文件“ /home/sultan/Repository/Django/monitor/app/request.py”,第236行
    浏览器= Firefox(配置文件)
  __init__中的文件“ /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py”,第46行
    self.binary,超时),
  __init__中的文件“ /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py”,第46行
    self.binary.launch_browser(self.profile)
  在launch_browser中的第44行,文件“ /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py”
    self._wait_until_connectable() 
  _wait_until_connectable中的文件“ /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py”,第87行
    引发WebDriverException(“无法加载配置文件。配置文件目录:%s”%self.profile.path)
selenium.common.exceptions.WebDriverException:无法加载配置文件。个人档案目录:/ tmp / webdriver-py-profilecopy

怎么了?我该如何解决这个问题?

Per this previous question I updated Selenium to version 2.0.1 But now I have another error, even when the profile files exist under /tmp/webdriver-py-profilecopy:

  File "/home/sultan/Repository/Django/monitor/app/request.py", line 236, in perform
    browser = Firefox(profile)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 46, in __init__
    self.binary, timeout),
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 46, in __init__
    self.binary.launch_browser(self.profile)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 44, in launch_browser
    self._wait_until_connectable() 
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 87, in _wait_until_connectable
    raise WebDriverException("Can't load the profile. Profile Dir : %s" % self.profile.path)
selenium.common.exceptions.WebDriverException: Can't load the profile. Profile Dir : /tmp/webdriver-py-profilecopy

What is wrong? How can I resolve this issue?


回答 0

更新:

硒团队已修复最新版本。对于几乎所有环境,修复程序都是:

点安装-U硒

尚不清楚它是在哪个版本上修复的(显然是r13122),但肯定是在2.26.0(更新时为最新)上已修复。


此错误意味着_wait_until_connectable超时,因为某些原因,代码无法连接到已加载到firefox中的webdriver扩展。

我刚刚向selenium报告了一个错误,在此我收到此错误,因为我正尝试使用代理,并且firefox接受了配置文件中4个配置的更改中的2个,因此未配置该代理与扩展名。不知道为什么会这样…

https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/2061

Update:

Selenium team fixed in latest version. For almost all environments the fix is:

pip install -U selenium

Unclear at which version it was fixed (apparently r13122), but certainly by 2.26.0 (current at time of update) it is fixed.


This error means that _wait_until_connectable is timing out, because for some reason, the code cannot connect to the webdriver extension that has been loaded into the firefox.

I have just reported an error to selenium where I am getting this error because I’m trying to use a proxy and only 2 of the 4 configured changes in the profile have been accepted by firefox, so the proxy isn’t configured to talk to the extension. Not sure why this is happening…

https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/2061


回答 1

将Ubuntu升级到12.04后,我遇到了同样的问题。

该问题在软件包方面,已在库的最新版本中修复。只需更新硒库。对于几乎所有的Python环境,这是:

pip install -U selenium

I had the same issue after upgrading Ubuntu to 12.04.

The issue was on the package side and has been fixed in the latest version of the library. Just update the selenium library. For almost all Python environments this is:

pip install -U selenium

回答 2

我遇到了FF 32.0和Selenium selenium-2.42.1-py2.7.egg相同的问题。试图更新硒,但是它已经是最新版本。解决方案是将Firefox降级到版本30。过程如下:

#Download version 30 for Linux (This is the 64 bit)
wget http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/30.0/linux-x86_64/en-US/firefox-30.0.tar.bz2

tar -xjvf firefox-30.0.tar.bz2
#Remove the old version
sudo rm -rf /opt/firefox*
sudo mv firefox /opt/firefox30.0
#Create a permanent link
sudo ln -sf /opt/firefox30.0/firefox /usr/bin/firefox

这样就解决了所有问题,并且这种组合效果更好!

I faced the same problem with FF 32.0 and Selenium selenium-2.42.1-py2.7.egg. Tried to update selenium, but it is already the latest version. The solution was to downgrade Firefox to version 30. Here is the process:

#Download version 30 for Linux (This is the 64 bit)
wget http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/30.0/linux-x86_64/en-US/firefox-30.0.tar.bz2

tar -xjvf firefox-30.0.tar.bz2
#Remove the old version
sudo rm -rf /opt/firefox*
sudo mv firefox /opt/firefox30.0
#Create a permanent link
sudo ln -sf /opt/firefox30.0/firefox /usr/bin/firefox

This solved all the problems, and this combination works better !


回答 3

作为对Jeff Hoye答案的扩展,一种更“ Pythonic”的方式将是webdriver.firefox.firefox_profile.FirefoxProfile如下子类化:

class CygwinFirefoxProfile(FirefoxProfile):
    @property
    def path(self):
        path = self.profile_dir
        # Do stuff to the path as described in Jeff Hoye's answer
        return path

然后,创建驱动程序:

driver = webdriver.Firefox(firefox_profile=CygwinFirefoxProfile())

As an extension to Jeff Hoye‘s answer, a more ‘Pythonic’ way would be to subclass webdriver.firefox.firefox_profile.FirefoxProfile as follows:

class CygwinFirefoxProfile(FirefoxProfile):
    @property
    def path(self):
        path = self.profile_dir
        # Do stuff to the path as described in Jeff Hoye's answer
        return path

Then, to create your driver:

driver = webdriver.Firefox(firefox_profile=CygwinFirefoxProfile())

回答 4

如果pip install -U selenium不起作用(就我而言,它不起作用),请尝试将Firefox降级到以前的版本。

我安装了Firefox 49.0,并降级到45.0,以确保selenium支持该版本。那时,它工作得很好。

这是降级到Firefox 45.0的快速方法:

sudo apt-get install firefox=45.0.2+build1-0ubuntu1

希望这可以帮助。

If pip install -U selenium doesn’t work (it didn’t, in my case), try downgrading your Firefox to a previous version.

I had Firefox 49.0 and downgraded to 45.0 to make sure the version is supported by selenium. It worked perfectly then.

Here’s a fast way to downgrade to Firefox 45.0:

sudo apt-get install firefox=45.0.2+build1-0ubuntu1

Hope this helps.


回答 5

如果您从cygwin运行webdriver,则问题在于配置文件的路径仍为POSIX格式,这会混淆Windows程序。我的解决方案使用cygpath将其转换为Windows格式。

在此文件/方法中:selenium.webdriver.firefox.firefox_binary.launch_browser():

更换:

    self._start_from_profile_path(self.profile.path)

与:

    from subprocess import Popen, PIPE
    proc = Popen(['cygpath','-d',self.profile.path], stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    path = stdout.split('\n', 1)[0]

    self._start_from_profile_path(path)
    #self._start_from_profile_path(self.profile.path)

由于Python甚至与我的主要编程语言都不接近,因此如果有人可以推荐一种更Python化的方法,也许我们可以将其推入发行版。如果它在开箱即用的Cygwin中工作肯定会很方便。

If you are running webdriver from cygwin, the problem is that the path to the profile is still in POSIX format which confuses windows programs. My solution uses cygpath to convert it into Windows format.

in this file/method: selenium.webdriver.firefox.firefox_binary.launch_browser():

replace:

    self._start_from_profile_path(self.profile.path)

with:

    from subprocess import Popen, PIPE
    proc = Popen(['cygpath','-d',self.profile.path], stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate()
    path = stdout.split('\n', 1)[0]

    self._start_from_profile_path(path)
    #self._start_from_profile_path(self.profile.path)

Since Python is not even close to my primary programming language, if someone can recommend a more pythonic approach maybe we can push it into the distribution. It sure would be handy if it worked in cygwin right out of the box.


回答 6

我遇到了同样的问题,并认为这是硒/ Firefox的错误组合。原来,我的.mozilla /文件夹权限仅可由root用户访问。做的chmod 770 ~/.mozilla/did俩。我建议在进一步排除故障之前确保这不是问题。

I had the same problem and believed it was the wrong combo of selenium / Firefox. Turned out that my .mozilla/ folder permissions were only accessible to the root user. Doing chmod 770 ~/.mozilla/ did the trick. I would suggest making sure this is not the issue before troubleshooting further.


回答 7

pip install -U selenium

我遇到了相同的问题,Firefox 34.0.5 (Dec 1, 2014)并将Selenium从升级2.42.12.44.0解决了我的问题。

但是,此后我又看到了这个问题,我认为是2.44.0,并进行了另一次升级。因此,我想知道是否可以通过简单地卸载然后重新安装来解决该问题。如果是这样,我不确定那将表明潜在的问题是什么。

pip install -U selenium

I had this same issue with Firefox 34.0.5 (Dec 1, 2014) and upgrading Selenium from 2.42.1 to 2.44.0 resolved my issue.

However, I’ve have since seen this issue again, I think with 2.44.0, and another upgrade fixed it. So I’m wondering if it might be fixed by simply uninstalling and then re-installing. If so, I’m not sure what that would indicate the underlying problem is.


回答 8

我正在使用硒2.53和55.0版的Firefox。我安装了较旧版本的firefox(46.0.1)解决了此问题,因为硒2.53不适用于47.0及更高版本的firefox。

I was using selenium 2.53 and firefox version 55.0. I solved this issue by installing the older version of firefox (46.0.1) since selenium 2.53 will not work for firefox version 47.0 & above.


回答 9

这不是一个适当的解决方案,但对我有用,如果有人可以改善,我将很高兴知道。我只是以root用户身份运行脚本sudo python myscript.py。我想我可以通过更改配置文件默认文件或目录来解决。

This is not a proper solution but worked for me, if somebody can improve I would be glad to know. I just run my script as root: sudo python myscript.py. I guess I can solve by changing the profile default file or directory could work.


如何使用Python + Selenium WebDriver保存和加载Cookie

问题:如何使用Python + Selenium WebDriver保存和加载Cookie

如何将Python的Selenium WebDriver中的所有cookie保存到txt文件,然后稍后加载?该文档没有对getCookies函数做太多说明。

How can I save all cookies in Python’s Selenium WebDriver to a txt-file, then load them later? The documentation doesn’t say much of anything about the getCookies function.


回答 0

您可以使用pickle将当前cookie保存为python对象。例如:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

然后再将它们添加回去:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

You can save the current cookies as a python object using pickle. For example:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

and later to add them back:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

回答 1

当您需要从一个会话到另一个会话的cookie时,还有另一种方法可以使用Chrome选项user-data-dir,以便将文件夹用作配置文件,我运行:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

您可以在此处执行检查人机交互的登录,然后执行此操作,然后每次使用该文件夹启动Webdriver时都需要我现在需要的cookie。您还可以手动安装扩展,并在每个会话中使用它们。在我运行的第二个时间里,所有的cookie都在那里:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see  the cookies, the settings, extensions, etc, and the logins done in the previous session are present here. 

好处是您可以使用具有不同设置和Cookie的多个文件夹,无需加载,卸载Cookie,安装和卸载扩展程序,更改设置,通过代码更改登录名的扩展程序,因此无法中断程序的逻辑,等等这比通过代码完成所有操作要快。

When you need cookies from session to session there is another way to do it, use the Chrome options user-data-dir in order to use folders as profiles, I run:

#you need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

You can do here the logins that check for human interaction, I do this and then the cookies I need now every-time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session. Secon time I run, all the cookies are there:

#you need to: from selenium.webdriver.chrome.options import Options    
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see  the cookies, the settings, extensions, etc, and the logins done in the previous session are present here. 

The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc Also this is faster than havin to do it all by code.


回答 2

请记住,您只能为当前域添加cookie。如果您想为您的Google帐户添加Cookie,请执行

browser.get('http://google.com')
for cookie in cookies:
    browser.add_cookie(cookie)

Remember, you can only a add cookie for the current domain. If you wanna add a cookie for your Google account, do

browser.get('http://google.com')
for cookie in cookies:
    browser.add_cookie(cookie)

回答 3

基于@Eduard Florinescu的回答,但添加了更新的代码和缺少的导入:

$ cat work-auth.py 
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data") 
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py 
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

Based on answer by @Eduard Florinescu but with newer code and missing import added:

$ cat work-auth.py 
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data") 
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py 
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

回答 4

@Roel Van de Paar编写的代码仅作了少许修改,所有功劳都归功于他。我在Windows中使用它,并且在设置和添加Cookie方面都运行良好:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com')  # Already authenticated
time.sleep(30)

Just a slight modification for the code written by @Roel Van de Paar, as all credit goes to him. I am using this in Windows and it is working perfectly, both for setting and adding cookies:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com')  # Already authenticated
time.sleep(30)

回答 5

这是我在Windows中使用的代码,它有效。

 for item in COOKIES.split(';'):
            name,value = item.split('=',1)
            name=name.replace(' ','').replace('\r','').replace('\n','')
            value = value.replace(' ','').replace('\r','').replace('\n','')
            cookie_dict={  
                    'name':name,
                    'value':value,
                    "domain": "",  # google chrome
                    "expires": "",
                    'path': '/',
                    'httpOnly': False,
                    'HostOnly': False,
                    'Secure': False
                    }
            self.driver_.add_cookie(cookie_dict)

this is code I used in windows, It works.

 for item in COOKIES.split(';'):
            name,value = item.split('=',1)
            name=name.replace(' ','').replace('\r','').replace('\n','')
            value = value.replace(' ','').replace('\r','').replace('\n','')
            cookie_dict={  
                    'name':name,
                    'value':value,
                    "domain": "",  # google chrome
                    "expires": "",
                    'path': '/',
                    'httpOnly': False,
                    'HostOnly': False,
                    'Secure': False
                    }
            self.driver_.add_cookie(cookie_dict)

回答 6

我的操作系统是Windows 10,Chrome版本是75.0.3770.100。我已经尝试过’user-data-dir’解决方案,但是没有用。尝试@ Eric Klien的解决方案也失败。最后,我将chrome设置设置为图片,它可以工作!但是在Windows Server 2012上却不起作用。

设置

my os is Windows 10, and the chrome version is 75.0.3770.100. I have tried the ‘user-data-dir’ solution, didn’t work. try the solution of @ Eric Klien fails too. finally, I make the chrome setting like the picture, it works!but it didn’t work on windows server 2012.

setting


获取Selenium中Javascript代码的返回值

问题:获取Selenium中Javascript代码的返回值

我正在使用Selenium2对我的网站进行一些自动化测试,并且希望能够获得一些Javascript代码的返回值。如果我的foobar()网页中有Javascript函数,并且想调用该函数并将返回值获取到我的Python代码中,该怎么做?

I’m using Selenium2 for some automated tests of my website, and I’d like to be able to get the return value of some Javascript code. If I have a foobar() Javascript function in my webpage and I want to call that and get the return value into my Python code, what can I call to do that?


回答 0

要返回值,只需return在传递给execute_script()方法的字符串中使用JavaScript关键字,例如

>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/foo/bar")
>>> wd.execute_script("return 5")
5
>>> wd.execute_script("return true")
True
>>> wd.execute_script("return {foo: 'bar'}")
{u'foo': u'bar'}
>>> wd.execute_script("return foobar()")
u'eli'

To return a value, simply use the return JavaScript keyword in the string passed to the execute_script() method, e.g.

>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/foo/bar")
>>> wd.execute_script("return 5")
5
>>> wd.execute_script("return true")
True
>>> wd.execute_script("return {foo: 'bar'}")
{u'foo': u'bar'}
>>> wd.execute_script("return foobar()")
u'eli'

回答 1

即使您没有像下面的示例代码中那样将代码的片段作为函数编写,也可以通过return var;在最后添加var是要返回的变量的方式来返回值。

result = driver.execute_script('''cells = document.querySelectorAll('a');
URLs = []
console.log(cells);
[].forEach.call(cells, function (el) {
    if(el.text.indexOf("download") !== -1){
    //el.click();
    console.log(el.href)
    //window.open(el.href, '_blank');
    URLs.push(el.href)
    }
});
return URLs''')

result将包含在URLs这种情况下的数组。

You can return values even if you don’t have your snipped of code written as a function like in the below example code, by just adding return var; at the end where var is the variable you want to return.

result = driver.execute_script('''
cells = document.querySelectorAll('a');
URLs = [];
[].forEach.call(cells, function (el) {
    URLs.push(el.href)
});
return URLs
''')

result will contain the array that is in URLs this case.


如何在Selenium Webdriver 2 Python中获取当前URL?

问题:如何在Selenium Webdriver 2 Python中获取当前URL?

我试图在Selenium中进行一系列导航后获取当前的URL。我知道红宝石有一个名为getLocation的命令,但是我找不到Python的语法。

I’m trying to get the current url after a series of navigations in Selenium. I know there’s a command called getLocation for ruby, but I can’t find the syntax for Python.


回答 0

使用current_url元素。例:

print browser.current_url

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)

回答 1

根据此文档(一个放置好东西的地方:)):

driver.current_url

或者,请参阅官方文档:https : //seleniumhq.github.io/docs/site/en/webdriver/browser_manipulation/#get-current-url

According to this documentation (a place full of goodies:)):

driver.current_url

or, see official documentation: https://seleniumhq.github.io/docs/site/en/webdriver/browser_manipulation/#get-current-url


回答 2

Selenium2Library具有get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

回答 3

另一种方法是检查chrome中的网址栏,找到该元素的id,让WebDriver单击该元素,然后使用selenium中的通用键功能发送用于复制和粘贴的键,然后打印出来或将其存储为变量等。

Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.


在Chrome中运行Selenium WebDriver python绑定

问题:在Chrome中运行Selenium WebDriver python绑定

使用Selenium时遇到问题。对于我的项目,我必须使用Chrome。但是,用Selenium启动该浏览器后,我无法连接到该浏览器。

由于某些原因,Selenium本身无法找到Chrome。当我尝试启动Chrome而没有添加路径时,会发生以下情况:

Traceback (most recent call last):
  File "./obp_pb_get_csv.py", line 73, in <module>
    browser = webdriver.Chrome() # Get local session of chrome
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__
    self.service.start()
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/service.py", line 58, in start
    and read up at http://code.google.com/p/selenium/wiki/ChromeDriver")
selenium.common.exceptions.WebDriverException: Message: 'ChromeDriver executable needs to be available in the path.                 Please download from http://code.google.com/p/selenium/downloads/list                and read up at http://code.google.com/p/selenium/wiki/ChromeDriver'

为了解决此问题,我随后在启动Chrome的代码中包含了Chromium路径。但是,解释器无法找到要连接的套接字:

Traceback (most recent call last):
  File "./obp_pb_get_csv.py", line 73, in <module>
    browser = webdriver.Chrome('/usr/bin/chromium') # Get local session of chrome
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__
    self.service.start()
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/service.py", line 64, in start
    raise WebDriverException("Can not connect to the ChromeDriver")
selenium.common.exceptions.WebDriverException: Message: 'Can not connect to the ChromeDriver'

我还尝试通过以下方式启动chrome解决问题:

铬--remote-shell-port = 9222

但是,这也不起作用。

PS。以下是有关我的系统的一些信息:

www-client:铬15.0.874.121  
dev-lang:python 2.7.2-r3 Selenium 2.11.1  
操作系统:GNU / Linux Gentoo Kernel 3.1.0-gentoo-r1

I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can’t connect to that browser after launching it with Selenium.

For some reason, Selenium can’t find Chrome by itself. This is what happens when I try to launch Chrome without including a path:

Traceback (most recent call last):
  File "./obp_pb_get_csv.py", line 73, in <module>
    browser = webdriver.Chrome() # Get local session of chrome
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__
    self.service.start()
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/service.py", line 58, in start
    and read up at http://code.google.com/p/selenium/wiki/ChromeDriver")
selenium.common.exceptions.WebDriverException: Message: 'ChromeDriver executable needs to be available in the path.                 Please download from http://code.google.com/p/selenium/downloads/list                and read up at http://code.google.com/p/selenium/wiki/ChromeDriver'

To solve this problem, I then included the Chromium path in the code that launches Chrome. However, the interpreter fails to find a socket to connect to:

Traceback (most recent call last):
  File "./obp_pb_get_csv.py", line 73, in <module>
    browser = webdriver.Chrome('/usr/bin/chromium') # Get local session of chrome
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 46, in __init__
    self.service.start()
  File "/usr/lib64/python2.7/site-packages/selenium/webdriver/chrome/service.py", line 64, in start
    raise WebDriverException("Can not connect to the ChromeDriver")
selenium.common.exceptions.WebDriverException: Message: 'Can not connect to the ChromeDriver'

I also tried solving the problem by launching chrome with:

chromium --remote-shell-port=9222

However, this did not work either.

PS. Here’s some information about my system:

www-client: chromium 15.0.874.121  
dev-lang:   python 2.7.2-r3 Selenium 2.11.1  
OS:         GNU/Linux Gentoo Kernel 3.1.0-gentoo-r1

回答 0

您需要确保独立的ChromeDriver二进制文件(与Chrome浏览器二进制文件不同)位于您的路径中或在webdriver.chrome.driver环境变量中可用。

有关如何进行整理的完整信息,请参见http://code.google.com/p/selenium/wiki/ChromeDriver

编辑:

是的,似乎是从路径环境变量读取chromedriver二进制文件的Python绑定中的错误。似乎chromedriver不在您的路径中,您必须将其作为参数传递给构造函数。

import os
from selenium import webdriver

chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()

You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.

see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up.

Edit:

Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.

import os
from selenium import webdriver

chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()

回答 1

对于Linux

  1. 检查您是否安装了最新版本的Chrome浏览器-> chromium-browser -version
  2. 如果没有,请安装最新版本的chrome sudo apt-get install chromium-browser
  3. 此处获取适当版本的chrome驱动程序
  4. 解压缩chromedriver.zip
  5. 将文件移到/usr/bin目录sudo mv chromedriver /usr/bin
  6. 转到/usr/bin目录cd /usr/bin
  7. 现在,您需要运行类似sudo chmod a+x chromedriver将其标记为可执行文件的操作。
  8. 最后,您可以执行代码。

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://www.google.com")
    print driver.page_source.encode('utf-8')
    driver.quit()
    display.stop()

For Linux

  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 cd /usr/bin
  7. Now, you would need to run something like sudo chmod a+x chromedriver to mark it executable.
  8. finally you can execute the code.

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://www.google.com")
    print driver.page_source.encode('utf-8')
    driver.quit()
    display.stop()
    

回答 2

仅Mac OSX

进行以下操作的更简单方法(假设您已经安装了自制软件,如果没有,应该先这样做,然后让自制软件使您的生活变得更好),只需运行以下命令:

brew install chromedriver

那应该将chromedriver放在您的路径中,并且您已经准备就绪。

Mac OSX only

An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:

brew install chromedriver

That should put the chromedriver in your path and you should be all set.


回答 3

对于窗户

从此直接链接 下载ChromeDriver 从此页面获取最新版本

将该chromedriver.exe文件粘贴到C:\Python27\Scripts文件夹中。

现在应该可以使用:

from selenium import webdriver
driver = webdriver.Chrome()

For windows

Download ChromeDriver from this direct link OR get the latest version from this page.

Paste the chromedriver.exe file in your C:\Python27\Scripts folder.

This should work now:

from selenium import webdriver
driver = webdriver.Chrome()

回答 4

对于窗户,请chromedriver.exe放在下面<Install Dir>/Python27/Scripts/

For windows, please have the chromedriver.exe placed under <Install Dir>/Python27/Scripts/


回答 5

有两种方法可以在Google Chrome浏览器中运行Selenium python测试。我正在考虑Windows(以Windows 10为例):

先决条件:从以下网址下载最新的Chrome驱动程序:https : //sites.google.com/a/chromium.org/chromedriver/downloads

方法1:

i)将下载的zip文件解压缩到您选择的目录/位置中
ii)如下所示在代码中设置可执行路径:

self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')

方式2:

i)只需将chromedriver.exe粘贴在/ Python / Scripts /下(在我的情况下,文件夹为:C:\ Python36 \ Scripts)
ii)现在编写如下的简单代码:

self.driver = webdriver.Chrome()

There are 2 ways to run Selenium python tests in Google Chrome. I’m considering Windows (Windows 10 in my case):

Prerequisite: Download the latest Chrome Driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads

Way 1:

i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:

self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')

Way 2:

i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:

self.driver = webdriver.Chrome()

回答 6

对于Windows的IDE:

如果您的路径不起作用,则可以尝试将其添加chromedriver.exe到您的项目中,就像在此项目结构中一样。

然后,您应该chromedriver.exe在主文件中加载。至于我,我装了driver.exedriver.py

def get_chrome_driver():
return webdriver.Chrome("..\\content\\engine\\chromedriver.exe",
                            chrome_options='--no-startup-window')

..表示driver.py's上层目录

. 表示目录 driver.py位于

希望这会有所帮助。

For Windows’ IDE:

If your path doesn’t work, you can try to add the chromedriver.exe to your project, like in this project structure.

Then you should load the chromedriver.exe in your main file. As for me, I loaded the driver.exe in driver.py.

def get_chrome_driver():
return webdriver.Chrome("..\\content\\engine\\chromedriver.exe",
                            chrome_options='--no-startup-window')

.. means driver.py's upper directory

. means the directory where the driver.py is located

Hope this will be helpful.