【问题标题】:Python : Scraping Instagram IGTV data, but it only shows information about first 24 recordsPython:抓取 Instagram IGTV 数据,但仅显示前 24 条记录的信息
【发布时间】:2021-05-14 00:52:25
【问题描述】:

我正在尝试抓取 instagram IGTV 数据(例如,视频标题、观看次数、喜欢、cmets 等)。首先我只使用 BeautifulSoup,但我只能获取前 12 个视频详细信息.然后我开始使用 Selenium,现在我可以获得前 24 个视频细节。但我必须刮掉所有的视频。

下面的代码为我提供了前 24 个视频的超链接,然后我从每个超链接中抓取视频详细信息:

import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#import json

url = 'https://www.instagram.com/agt/channel/?hl=en'
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=options)
driver.get(url)
time.sleep(3)
page = driver.page_source
driver.quit()
soup = BeautifulSoup(page, 'html.parser')

#print(soup)
video_links=[]
for a in soup.find_all('a', class_='_bz0w', href=True):
    video_links.append('https://www.instagram.com' + a['href'])
print(video_links)

请建议我如何获取所有视频详细信息。

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    您可能需要向下滚动才能加载更多结果。 你可以做类似的事情

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

    这样做

    将此与找到的答案 elsewhere 结合起来,这样我们就可以向下滚动直到到达页面末尾:

    import time
    from bs4 import BeautifulSoup
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    #import json
    
    url = 'https://www.instagram.com/agt/channel/?hl=en'
    options = Options()
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(chrome_options=options)
    driver.get(url)
    SCROLL_PAUSE_TIME = 1
    
    # Get scroll height
    last_height = driver.execute_script("return document.body.scrollHeight")
    
    while True:
        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)
    
        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height
    
    
    page = driver.page_source
    driver.quit()
    soup = BeautifulSoup(page, 'html.parser')
    
    #print(soup)
    video_links=[]
    
    for a in soup.find_all('a', class_='_bz0w', href=True):
        video_links.append('https://www.instagram.com' + a['href'])
    print(len(video_links))
    

    【讨论】:

    • 即使在使用了这个之后,我也获得了最多 24 个超链接。频道链接有 100 多个视频
    • 请看我的编辑。这给了我 41 个链接。可能需要使用 scroll_pause_time 值
    • 此代码返回大约 37 个结果,但没有任何顺序。我希望获得前 37 个 href
    • 您可以调整代码以在滚动之间获取结果
    • 我试过了,还是不行,伙计。在每次执行时,它都会生成不同的 hrefs。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多