无法使用Selenium和Python在Instagram上滚动likers页面

2024-04-19 06:09:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图建立一个网络刮板,让我刮的'喜欢'的名字在Instagram上的帖子。我可以自动打开instagram,登录,发帖,打开“喜欢的人”列表。 The step I could reach

接下来是代码,目的是删除喜欢的人的名字。由于一次只显示最喜欢的11个人,其余的人只有在滚动后才会显示(这会触发一个AJAX请求,正如我从其他有类似问题的人那里读到的那样),所以我编写了这段代码,它应该将前11个名字刮除,附加到一个列表中,打印出来,然后滚动。你知道吗

no_of_pagedowns = 5

while no_of_pagedowns:

    liker_list = []
    likers = driver.find_elements_by_class_name("qyrsm")    

    for n in likers:

        #scrape the name of the likers
        liker = n.find_element_by_class_name("_4EzTm").get_attribute("textContent")
        liker_list.append(liker)

    no_of_pagedowns -= 1

    print(liker_list)

    time.sleep(1)

    driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div/div')

    #scrollcode
    driver.execute_script("javascript:window.scrollBy(0,660)") 

它工作,可以返回前11个“喜欢者”的名字,但它不会滚动。我认为问题是代码没有集中在正确的元素上,但是我没有找到应该集中在哪个元素上。它只给同样的11个人5次。我还试着替换

    driver.execute_script("javascript:window.scrollBy(0,660)") 

像这样的

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")

或者

    elem.send_keys(Keys.PAGE_DOWN)

where elem = driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div/div')

我也试过这段代码:

no_of_pagedowns = 5

while no_of_pagedowns:

    liker_list = []
    likers = driver.find_elements_by_class_name("qyrsm")    

    for n in likers:

        #scrape the name of the likers
        liker = n.find_element_by_class_name("_4EzTm").get_attribute("textContent")
        liker_list.append(liker)

    no_of_pagedowns -= 1

    print(liker_list)

    time.sleep(1)

    driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div/div').click()

    driver.execute_script("window.scrollBy(0, 660);")

在找到元素后,我放了一个.click(),因为我认为可能需要单击来关注“liker list”,它实际上使滚动发生了。但是现在又出现了另一个问题:不管我输入的y cood值是多少,它每次只向下滚动1个liker,在第5个循环中,它失败了,因为它会单击从顶部开始计数的第6个liker,导致第6个liker的个人资料页。你知道吗

我已经陷入这个滚动问题差不多一个星期了。我在谷歌上搜索和阅读了很多人的类似问题,只是找不到一个有帮助的。我真的很感激任何能帮忙的人。你知道吗


Tags: ofno代码namedivbydriverelement
1条回答
网友
1楼 · 发布于 2024-04-19 06:09:14

我不知道你到底在寻找什么,但这里是我在java中尝试时,我们面临的滚动问题。元素不会自动滚动到视图中,并且会滚动设置的对象数,因此我们编写了下面的代码

   public static void scrollintoView(WebDriver driver, String Value) throws 
   InterruptedException {

    int totalAttempts = 30;

    while (totalAttempts > 0) { 

        totalAttempts = totalAttempts-1;


        try { // checks code for exceptions

            WebElement ele=  driver.findElement(By.xpath(Value));

            break; // if no exceptions breaks out of loop
        } 
        catch (org.openqa.selenium.NoSuchElementException e) { 

            JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("window.scrollBy(0, 300)");


          continue; // continues to loop if exception is found

        }}

    }

您可以在python中尝试类似的操作,硬滚动可以设置每个滚动中要检查的用户数。 如果有用的话请告诉我

相关问题 更多 >