爬虫返回空结果

2 投票
1 回答
618 浏览
提问于 2025-06-18 04:00

我正在尝试制作一个抓取工具,用来获取Epic Games商店免费游戏的链接。

这里插入图片描述

headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",}
result = requests.get("https://www.epicgames.com/store/en-US/free-games?sessionInvalidated=true", 
headers=headers)
soup = BeautifulSoup(result.content, 'lxml')
urls = []
links = []
urls = soup.find('div', {'class': 'CardGrid-group_c5363b6a'}).find_all("a")
return urls

这里插入图片描述

但是它总是返回空值,我看不出哪里出了问题。

相关问题:

  • 暂无相关问题
暂无标签

1 个回答

3

这个页面使用 JavaScript 来添加一些元素,但 requestsBeautifulSoup 是无法运行 JavaScript 的。

不过,通常情况下,JavaScript 会从网址中读取数据,你可以在 FirefoxChromeDevTools 中找到这些网址(在 Network 标签下,过滤器选择 XHR),然后你可以用这些网址来读取 JSON 格式的数据,这样你就不需要使用 BeautifulSoup 了。

import requests

url = 'https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=PL&allowCountries=PL'

r = requests.get(url)

data = r.json()

#print(r.text)

for item in data['data']['Catalog']['searchStore']['elements']:
    print(item['title'])
    offers = item['promotions']['promotionalOffers']
    for offer in offers:
        print(offer['promotionalOffers'][0]['startDate'])
        print(offer['promotionalOffers'][0]['endDate'])

结果

Mystery Game
Grand Theft Auto V
2020-05-14T15:00:00.000Z
2020-05-21T15:00:00.000Z

你可能需要深入查看 data 来获取其他详细信息。

顺便说一下:你可能需要为 countryallowCountries 使用不同的值。

撰写回答