网络抓取的性能改进?

作为个人项目的一部分,我尝试编写一个网络抓取工具,它访问我的 Instagram 帐户以抓取给定对话中的所有 DM。


在某种程度上,它工作得很好;我的问题是我试图抓取的群组对话非常活跃并且可以追溯到 2017 年(因此它有很多消息),并且在某些时候,chromeengine 非常滞后以至于整个事情超时并崩溃.

有什么办法可以提高性能吗?也许我应该用一种完全不同的方式来做这件事?


def userlist():

    #create my selenium instance

    options = webdriver.ChromeOptions()

    #options.add_argument('headless')

    options.add_argument('window-size=1200x600')

    driver = webdriver.Chrome(chrome_options=options)


    #Log into instagram

    driver.get("https://instagram.com")

    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.NAME, "username")))

    driver.find_element_by_name("username").send_keys("###############")

    driver.find_element_by_name("password").send_keys("###############")

    drive.findelement_by_xpath("//button[contains(@class, 'sqdOP  L3NKy   y3zKF     ')]").click()

    sleep(5)

    driver.find_element_by_xpath("//button[contains(@class, 'sqdOP yWX7d    y3zKF     ')]").click()

    sleep(3)

    driver.find_element_by_xpath('//button[contains(@class, "aOOlW   HoLwm ")]').click()

    sleep(1)


    #go to the group convo

    driver.get("https://instagram.com/direct/inbox")

    sleep(3)

    driver.find_element_by_xpath(

        '//a[contains(@href, "/direct/t/###################")]').click()

    sleep(1)

    print("Verbindung zur Gruppe hergestellt!")

    print("")

    print("Beginne Auszählung, bitte etwas Geduld haben...")


    #scroll to the top to load older messages, until that isn't possible anymore - do this by checking for scrollTop > 0 every 3 seconds

    i = 1

    while int(driver.find_element_by_xpath('//div[contains(@class, "frMpI  -sxBV")]').get_attribute("scrollTop")) > 0:

        driver.execute_script("document.getElementsByClassName('frMpI  -sxBV')[0].scrollTop = 0")

        sleep(3)

        print(f"Schritt {i}...")

        print("")

        i += 1

    print("")


PIPIONE
浏览 68回答 1
1回答

30秒到达战场

好的,如果您的问题出在 while 循环中,请尝试将此代码与 try 和 except 一起使用。while int(driver.find_element_by_xpath('//div[contains(@class, "frMpI  -sxBV")]').get_attribute("scrollTop")) > 0:    try:        driver.execute_script("document.getElementsByClassName('frMpI  -sxBV')[0].scrollTop = 0")        sleep(3)        print(f"Schritt {i}...")        print("")        i += 1    except Exception as e :        print(e)        i += 0此代码将打印错误并处理它并在出现错误时自动重播循环,因此您无需担心只需将此循环替换为您的 while 循环希望它可以帮助您
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python