问题
So basically i want to make a Facebook script that is going to add all friends from my friends "Friend List", now the problem is we already have a lot of mutual friends (that are shown on the top of the "Friend List"), I want to scroll all the way down until "Add Friend" appears, and once it appears I want the script to click the button and add him everyone else that is not my friend. Now I am pretty new to programming so if you can to explain me more in details how to do this PS: i know that this should be done in Java but can someone explain me how to do this in Python?
Here is the code:
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()
回答1:
This does not have to be done in Java, python will work just fine. You do not necessarily have to scroll to where add friends
appears, you can use the find_element_by_id
or any other method of finding elements and it will still locate it. But if you truely have your heart set on finding and scrolling to the element.
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()
The wait is to ensure that the
add friend
id loads before selenium starts searching for it, assuming it doesn't load with the page immediately. If selenium still doesn't seeadd friend
then I would recommend you make use ofexpected_condition
andWebDriverWait
, altough I very much doubt it will get to this
If an explicit wait does not work, then you should check if that portion of the page exists on an iframe or a different frame
来源:https://stackoverflow.com/questions/60590546/scroll-down-until-elements-are-found-in-python