通过find_element_by_class_name单击按钮不起作用python selenium webdriver不起作用 [英] Click button by find_element_by_class_name not working python selenium webdriver NOT working

查看:826
本文介绍了通过find_element_by_class_name单击按钮不起作用python selenium webdriver不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python和Selenium在LinkedIn上添加联系人。我尝试通过在网络标签中添加LinkedIn的联系建议来实现此目的( https:// www .linkedin.com / mynetwork ),它具有无限滚动功能。

I'm trying to add contacts on LinkedIn using Python and Selenium. I'm attempting to do so by adding the contact suggestions made by LinkedIn in the "Network" tab (https://www.linkedin.com/mynetwork), which has an infinite scroll feature.

基本上我希望脚本找到按钮连接,接下来在每个建议的配置文件中,单击按钮,然后重复进行操作,直到出现错误为止,由此脚本应向下滚动以加载更多连接按钮以进行重复。

Basically I want the script to locate the button "Connect", which is next to each suggested profile, click the button, and then repeat until error whereby the script should scroll down to load more "Connect" buttons to reiterate.

因为所有连接按钮都具有相同的类,所以可以通过find_element_by_class_name()找到找到按钮元素的位置。我也尝试过使用CSS和Xpath定位元素,但没有成功。

The best way I've found to locate the button element is by find_element_by_class_name() since all the connect buttons have the same class. I've also tried locating the elements using CSS and Xpath, without success.

问题:脚本可以单击第一个连接按钮,但此后没有一个。我尝试了许多实现想法(通过Xpath,CSS进行定位,并使用一系列按钮单击),但似乎没有一个可行。以下是脚本的相关部分。

PROBLEM: The script is able to click the first Connect button, but none after that. I've tried many ideas for implementation (locating by Xpath, CSS, using a list of buttons to click), yet none seem to work. Below is the relevant part of the script.

while True:
    try:
        driver.find_element_by_class_name("mn-person-card__person-btn-ext.button-secondary-medium").click()
        time.sleep(1)
    except:
        pass
        print("trying to scroll")
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(1) 

有什么想法吗?在我看来,似乎代码应该可以工作,并且似乎还有其他阻碍成功的因素。可能是错误或类似错误。可能会提到我在所有这些方面还很陌生,这是我尝试制作的用于操纵浏览器的第一个脚本。

Any ideas? To me it seems as if the code should work, and as if there is something else which is preventing success. Maybe a bug or similar. Might mention that I'm rather new to all of this, and it's the first script I'm trying to make to manipulate a browser.

我正在使用Firefox驱动程序。完整的脚本可以在这里找到: http://pastebin.com/qtdNsRtz

I'm using Firefox driver. Full script can be found here: http://pastebin.com/qtdNsRtz

谢谢!

推荐答案

您应该使用 find_elements 查找具有相同类的所有元素
尝试执行以下操作以获取所有元素:

You should use find_elements for finding all elements with same class Try this to get all elements:

elements = driver.find_elements_by_class_name("mn-person-card__person-btn-ext.button-secondary-medium")

然后使用for循环单击它们中的每个。例如:

then use a for loop to click each of them. For example:

for e in elements:
    e.click()

这篇关于通过find_element_by_class_name单击按钮不起作用python selenium webdriver不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆