【问题标题】:Scroll down until elements are found in Python向下滚动直到在 Python 中找到元素
【发布时间】:2020-03-08 18:09:31
【问题描述】:

所以基本上我想制作一个 Facebook 脚本来添加我朋友“朋友列表”中的所有朋友,现在的问题是我们已经有很多共同的朋友(显示在“朋友”的顶部列表”),我想一直向下滚动直到出现“添加朋友”,一旦出现,我希望脚本单击按钮并将他添加到其他不是我朋友的人中。现在我对编程很陌生,所以如果你能详细解释我如何做到这一点 PS:我知道这应该在 Java 中完成,但有人可以解释我如何在 Python 中做到这一点吗?

代码如下:

root.get(targets_url)        #targets_url is the link of targets friend list
time.sleep(10)

while True:
    element = root.find_element_by_class_name('FriendRequestAdd').click()

【问题讨论】:

    标签: javascript python-3.x selenium-webdriver scroll element


    【解决方案1】:

    这不必在 Java 中完成,python 可以正常工作。您不必滚动到出现add friends 的位置,您可以使用find_element_by_id 或任何其他查找元素的方法,它仍然会找到它。但是,如果您真的一心想要找到并滚动到元素。

    from selenium.webdriver.ui.support import expected_conditions as ec
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    
    wait = WebDriverWait(root)     
    
    root.wait(3) #wait for element to visible. implicit wait.
    
    #feel free to change XPATH to CSS_SELECTOR or whatever suits you
    friendlist = wait.until(ec.element_to_be_clickable((By.XPATH,'xpath value'))  #explicitly wait for element to appear on the page
    root.execute_script("arguments[0].ScrollIntoView;", friendlist)
    friendlist.click()
    

    等待是为了确保add friend id 在 selenium 之前加载 开始搜索它,假设它没有与页面一起加载 立即地。如果硒仍然看不到add friend,那么我会 建议您使用 expected_conditionWebDriverWait , 虽然我非常怀疑它会达到这个目标

    如果显式等待不起作用,那么您应该检查页面的该部分是否存在于 iframe 或不同的框架中

    【讨论】:

    • AttributeError: 'WebDriver' 对象没有属性 'sleep'
    • 我将 root.sleep() 更改为 time.sleep() 并将 root.find_element_by_id('addfriend') 更改为 root.find_element_by_class_name('FriendRequestAdd') 现在一旦向下滚动就会弹出此错误并添加朋友:“selenium.common.exceptions.ElementNotInteractableException: Message: Element
    • 我解释说,如果您无法通过隐式等待看到它,那么您应该尝试使用 WebDriverWait 进行显式等待。但是,我已经更新了我的代码来解释你应该做什么,并添加了新的说明来帮助你
    • 我真的很感谢这段时间,但由于某种原因,这仍然不起作用,您能否通过 Instagram(@dzonny17) 或 Facebook(Ludwig Vult) 与我联系,以便您可以详细解释我真的很想帮忙,我为此苦苦挣扎了一个多月,仍然找不到解决方案
    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 2016-04-11
    • 2021-09-13
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2015-01-17
    • 2019-04-07
    相关资源
    最近更新 更多