为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Selenium 在 Instagram 弹出框架中向下滚动

如何使用 Selenium 在 Instagram 弹出框架中向下滚动

跃然一笑 2021-10-10 16:46:54
我有一个 python 脚本,使用 selenium 转到给定的 Instagram 个人资料并遍历用户的关注者。在 instagram 网站上,当单击查看关注者列表时,会打开一个弹出窗口,其中列出了列出的帐户(这是该网站的屏幕截图)然而,无论是在视觉上还是在 html 中,都只显示了 12 个帐户。为了看到更多,必须向下滚动,所以我尝试使用 Keys.PAGE_DOWN 输入来执行此操作。from selenium import webdriverfrom selenium.common.exceptions         import TimeoutExceptionfrom selenium.webdriver.support.ui      import WebDriverWait from selenium.webdriver.support         import expected_conditions as ECfrom selenium.webdriver.chrome.options  import Optionsfrom selenium.webdriver.common.keys     import Keysimport time ...username = 'Username'password = 'Password'message  = 'blahblah'tryTime  = 2#create driver and log indriver = webdriver.Chrome()logIn(driver, username, password, tryTime)#gets rid of preference pop-upa = driver.find_elements_by_class_name("HoLwm")a[0].click()#go to profiledriver.get("https://www.instagram.com/{}/".format(username))#go to followers listfollowers = driver.find_element_by_xpath("//a[@href='/{}/followers/']".format(username))followers.click()time.sleep(tryTime) #find all li elements in listfBody  = 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 键发送到哪个元素,或者是否有另一种加载帐户的方法?任何帮助深表感谢!
查看完整描述

2 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

如果在 range(1, 4) 中为 i 的范围添加迭代 (for),则上述代码工作正常:尝试:


            #find all li elements in list

            fBody  = self.driver.find_element_by_xpath("//div[@class='isgrP']")

            scroll = 0

            while scroll < 5: # scroll 5 times

                self.driver.execute_script('arguments[0].scrollTop = arguments[0].scrollTop + arguments[0].offsetHeight;', fBody)

                time.sleep(2)

                scroll += 1


            fList  = self.driver.find_elements_by_xpath("//div[@class='isgrP']//li")

            print("fList len is {}".format(len(fList)))


        except Exception as e:

            print(e, "canot scrol")


        try:

            #get tags with a

            hrefs_in_view = self.driver.find_elements_by_tag_name('a')

            # finding relevant hrefs

            hrefs_in_view = [elem.get_attribute('title') for elem in hrefs_in_view]


            [pic_hrefs.append(title) for title in hrefs_in_view if title not in pic_hrefs]

            print("Check: pic href length " + str(len(pic_hrefs)))


        except Exception as tag:

            print(tag, "can not find tag")

因此,即使 while 循环未命中,for 循环也可以滚动


查看完整回答
反对 回复 2021-10-10
  • 2 回答
  • 0 关注
  • 205 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号