Skip to main content
 首页 » 编程设计

python之使用 python、selenium 和 pyvirtualdisplay 单击 web 元素时出现问题

2024年10月17日38mfryf

我有一个简单的网络爬虫,可以登录 Twitter,进入以下页面,然后通过单击齿轮图标从我所有的关注者(如果他们被静音等)获取信息。问题是单击功能在我的新计算机上已停止工作。

此外,我正在使用 Firefox() 网络驱动程序。

这是我正在使用的代码(您需要为 Twitter 添加您自己的凭据才能使其正常工作):https://gist.github.com/anonymous/4c64054d01af77ae2c5c2b39a2165d80

此代码在一台机器上运行良好,但无法在另一台机器上单击 dom 元素。以下是一些可能提供洞察力的规范。

::GOOD BOX:: 
pip packages 
- selenium 2.47.3 
- pyvirtualdisplay 0.1.5 
 
python 2.7 
firefox 41.0 
lib32z-dev 1:1.2.8.dfsg-1ubuntu1 
python-lxml 3.3.3-1ubuntu0.1 
python-dev 2.7.5-5ubuntu3 
build-essential 11.6ubuntu6 
 
------------------------- 
 
::BAD BOX:: 
pip packages 
- selenium 2.53.6 
- pyvirtualdisplay 0.2 
 
python 2.7 
firefox-mozilla-build 47.0.1-0ubuntu1 (not sure why I need this, the other box doesn't seem to have it.  But things break if I remove it) 
firefox 47.0.1 
python-dev 2.7.11-1 
libxml2-dev 2.9.3+dfsg1-1ubuntu0.1 
libxslt-dev (1.1.28-2.1) 
build-essential 12.1ubuntu2 

当我在“坏盒子”上运行这段代码并且没有捕捉到异常时,我得到以下信息:

selenium.common.exceptions.WebDriverException: Message: Element is not clickable at point (464, 1). Other element would receive the click: <div class="container"></div> 

请您参考如下方法:

这可能是由于窗口太小导致目标元素最终隐藏在另一个元素之下。尝试设置原始尺寸:

driver.set_window_size(1920, 1200) 

如果您的元素最终隐藏在顶部横幅下,您也可以尝试更改滚动行为:

DesiredCapabilities.FIREFOX["elementScrollBehavior"] = 1 #scroll bottom instead of top 
driver = webdriver.Firefox()