首页 > 解决方案 > 使用 Infinite Scroll 从网站抓取数据?

问题描述

我正在尝试为标题和其他项目抓取网站,但为了简洁起见,只是游戏标题。

我曾尝试同时使用硒和美丽的汤来获取标题,但无论我做什么,我似乎都无法获得所有 9 月的版本。事实上,我也获得了一些 8 月的游戏名称。我认为这与网站没有尽头的事实有关。我将如何仅获得 9 月的冠军头衔?下面是我使用的代码,我尝试使用 Scrolling,但我认为我不明白如何正确使用它。

编辑:我的目标是能够通过更改几行代码最终获得每个月。

from selenium import webdriver
from bs4 import BeautifulSoup

titles = []

chromedriver = 'C:/Users/Chase The Great/Desktop/Podcast/chromedriver.exe'
driver = webdriver.Chrome(chromedriver)
driver.get('https://www.releases.com/l/Games/2019/9/')
res = driver.execute_script("return document.documentElement.outerHTML")
driver.quit()
soup = BeautifulSoup(res, 'lxml')

for title in soup.find_all(class_= 'calendar-item-title'):
    titles.append(title.text)

我预计将获得 133 个头衔,而我将获得一些 8 月头衔,外加仅部分头衔,例如:

['SubaraCity', 'AER - Memories of Old', 'Vambrace: Cold Soul', 'Agent A: A Puzzle in Disguise', 'Bubsy: Paws on Fire!', 'Grand Brix Shooter', 'Legend of the Skyfish', 'Vambrace: Cold Soul', 'Obakeidoro!', 'Pokemon Masters', 'Decay of Logos', 'The Lord of the Rings: Adventure ...', 'Heave Ho', 'Newt One', 'Blair Witch', 'Bulletstorm: Duke of Switch Edition', 'The Ninja Saviors: Return of the ...', 'Re:Legend', 'Risk of Rain 2', 'Decay of Logos', 'Unlucky Seven', 'The Dark Pictures Anthology: Man ...', 'Legend of the Skyfish', 'Astral Chain', 'Torchlight II', 'Final Fantasy VIII Remastered', 'Catherine: Full Body', 'Root Letter: Last Answer', 'Children of Morta', 'Himno', 'Spyro Reignited Trilogy', 'RemiLore: Lost Girl in the Lands ...', 'Divinity: Original Sin 2 - Defini...', 'Monochrome Order', 'Throne Quest Deluxe', 'Super Kirby Clash', 'Himno', 'Post War Dreams', 'The Long Journey Home', 'Spice and Wolf VR', 'WRC 8', 'Fantasy General II', 'River City Girls', 'Headliner: NoviNews', 'Green Hell', 'Hyperforma', 'Atomicrops', 'Remothered: Tormented Fathers']

标签: pythonseleniumweb-scrapingbeautifulsoupinfinite-scroll

解决方案


在我看来,为了只获得 9 月,首先您只想获取 9 月的部分:

section = soup.find('section', {'class': 'Y2019-M9 calendar-sections'})

然后,一旦您获取 9 月的部分,就可以获取<a>标签中的所有标题,如下所示:

for title in section.find_all('a', {'class': ' calendar-item-title subpage-trigg'}):
    titles.append(title.text)

请注意,以前的都没有经过测试。

更新:问题是每次您要加载页面时,它只会为您提供仅包含 24 个项目的第一部分,为了访问它们,您必须向下滚动(无限滚动)。如果您打开浏览器开发者工具,选择Network然后XHR您会注意到每次滚动并加载下一个“页面”时,都会有一个url类似于以下内容的请求:

https://www.releases.com/calendar/nextAfter?blockIndex=139&itemIndex=23&category=Games®ionId=us

我的猜测是,这blockIndex意味着该月并且itemIndex适用于加载的每个页面,如果您只寻找 9 月blockIndex将始终139在该请求中,挑战是获取下一页itemIndex的下一页,以便您可以构建您的下一个要求。下一个itemIndex将始终是上itemIndex一个请求的最后一个。

我确实制作了一个脚本,它只做你想做的事BeautifulSoup。自行决定使用它,有一些常量可以动态提取,但我认为这可以让您抢先一步:

import json

import requests
from bs4 import BeautifulSoup

DATE_CODE = 'Y2019-M9'
LAST_ITEM_FIRST_PAGE = f'calendar-item col-xs-6 to-append first-item calendar-last-item {DATE_CODE}-None'
LAST_ITEM_PAGES = f'calendar-item col-xs-6 to-append calendar-last-item {DATE_CODE}-None'
INITIAL_LINK = 'https://www.releases.com/l/Games/2019/9/'
BLOCK = 139
titles = []


def get_next_page_link(div: BeautifulSoup):
    index = div['item-index']
    return f'https://www.releases.com/calendar/nextAfter?blockIndex={BLOCK}&itemIndex={index}&category=Games&regionId=us'


def get_content_from_requests(page_link):
    headers = requests.utils.default_headers()
    headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    req = requests.get(page_link, headers=headers)
    return BeautifulSoup(req.content, 'html.parser')


def scroll_pages(link: str):
    print(link)
    page = get_content_from_requests(link)
    for div in page.findAll('div', {'date-code': DATE_CODE}):
        item = div.find('a', {'class': 'calendar-item-title subpage-trigg'})
        if item:
            # print(f'TITLE: {item.getText()}')
            titles.append(item.getText())
    last_index_div = page.find('div', {'class': LAST_ITEM_FIRST_PAGE})
    if not last_index_div:
        last_index_div = page.find('div', {'class': LAST_ITEM_PAGES})
    if last_index_div:
        scroll_pages(get_next_page_link(last_index_div))
    else:
        print(f'Found: {len(titles)} Titles')
        print('No more pages to scroll finishing...')


scroll_pages(INITIAL_LINK)
with open(f'titles.json', 'w') as outfile:
    json.dump(titles, outfile)

如果您的目标是使用Selenium,我认为可能适用相同的原则,除非它在加载页面时具有滚动功能。更换INITIAL_LINK, DATE_CODE&BLOCK相应地,也会让你得到其他月份。


推荐阅读