hiM*_*Mom 4 python selenium webautomation instagram
我有一个 python 脚本,使用 selenium 转到给定的 Instagram 个人资料并遍历用户的关注者。在 Instagram 网站上,当单击查看关注者列表时,会弹出一个列出帐户的弹出窗口(这是该网站的屏幕截图)
然而,无论是在视觉上还是在 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
Run Code Online (Sandbox Code Playgroud)
...
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()
Run Code Online (Sandbox Code Playgroud)
当我尝试运行它时,出现以下错误:
Message: unknown error: cannot focus element
Run Code Online (Sandbox Code Playgroud)
我知道这可能是因为我为 使用了错误的元素fBody
,但我不知道哪个是正确的。有谁知道我应该将 PAGE_DOWN 键发送到哪个元素,或者是否有另一种方法来加载帐户?
任何帮助深表感谢!
eww*_*ink 10
你要找的元素//div[@class='isgrP']
而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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6361 次 |
最近记录: |