我有一个使用 selenium 的 python 脚本来访问给定的 Instagram 个人资料并迭代用户的关注者。在 Instagram 网站上,当点击查看关注者列表时,会打开一个弹出窗口,其中列出了帐户(这里是该网站的屏幕截图 https://i.stack.imgur.com/HDZAX.png)
然而,无论是在视觉上还是在 html 中,都只显示了 12 个帐户。为了查看更多内容,必须向下滚动,因此我尝试使用 Keys.PAGE_DOWN 输入执行此操作。
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
...
username = 'Username'
password = 'Password'
message = 'blahblah'
tryTime = 2
#create driver and log in
driver = webdriver.Chrome()
logIn(driver, username, password, tryTime)
#gets rid of preference pop-up
a = driver.find_elements_by_class_name("HoLwm")
a[0].click()
#go to profile
driver.get("https://www.instagram.com/{}/".format(username))
#go to followers list
followers = driver.find_element_by_xpath("//a[@href='/{}/followers/']".format(username))
followers.click()
time.sleep(tryTime)
#find all li elements in list
fBody = driver.find_element_by_xpath("//div[@role='dialog']")
fBody.send_keys(Keys.PAGE_DOWN)
fList = fBody.find_elements_by_tag("li")
print("fList len is {}".format(len(fList)))
time.sleep(tryTime)
print("ended")
driver.quit()
当我尝试运行此程序时,出现以下错误:
Message: unknown error: cannot focus element
我知道这可能是因为我使用了错误的元素fBody
,但我不知道哪个是正确的。有谁知道我应该将 PAGE_DOWN 键发送到哪个元素,或者是否有其他方法来加载帐户?
任何帮助深表感谢!
你正在寻找的元素是//div[@class='isgrP']
and Keys.PAGE_DOWN
不适用于可滚动的 div。
你的变量fList
保持旧值,滚动后需要再次查找元素。
#find all li elements in list
fBody = driver.find_element_by_xpath("//div[@class='isgrP']")
scroll = 0
while scroll < 5: # scroll 5 times
driver.execute_script('arguments[0].scrollTop = arguments[0].scrollTop + arguments[0].offsetHeight;', fBody)
time.sleep(tryTime)
scroll += 1
fList = driver.find_elements_by_xpath("//div[@class='isgrP']//li")
print("fList len is {}".format(len(fList)))
print("ended")
#driver.quit()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)