Как задать параметры при парсинге
Есть ссылка с которой надо парсить данные (https://www.epicgames.com/store/ru/browse?sortBy=releaseDate&sortDir=DESC&tag=Экшен&count=40&start=0), и есть код, который должен парсить, но он выдает пустой словарь каждый раз и я уверен, что проблема в ссылке, возможно надо отдельно задавать параметры ему, вот только как это правильно сделать? Код, который надо доработать:
import requests
from bs4 import BeautifulSoup
HOST = 'https://www.epicgames.com'
URL = 'https://www.epicgames.com/store/ru/browse?sortBy=releaseDate&sortDir=DESC&tag=Экшен&count=40&start=0'
HEADERS = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 YaBrowser/20.11.3.183 Yowser/2.5 Safari/537.36'
}
def get_html(url, params=None):
req = requests.get(url, headers=HEADERS, params=params)
return req
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='css-1gc10zu-DiscoverCardLayout__content')
games = []
for item in items:
games.append(
{
'TITLE': item('div', class_='css-2ucwu'),
}
)
return games
def parser():
html = get_html(URL)
games = []
if html.status_code == 200:
html = get_html(URL)
games.extend(get_content(html.text))
print(games)
else:
print('Error')
parser()
Ответы (2 шт):
Чтобы понять почему у тебя ничего не работает, достаточно просто посмотреть на сам запрос.
file = open('test.html', 'wb')
file.write(get_html(URL).text.encode('utf-8'))
file.close()
Подходящие для этого решение - это Epic Store API. (Спасибо 0dminnimda за этот вариант решения). Вот код, который просматривает каталоги магазина и выводит их название.
import requests
endpoint = "https://graphql.epicgames.com/graphql"
# В переменной query содержится сам запрос
query = b'{"query":"\\n query storefrontDiscoverQuery(\\n $locale:String,\\n $country:String\u0021\\n ) {\\n Storefront {\\n storefrontModules(locale: $locale) {\\n ... on StorefrontBreaker {\\n type\\n title\\n titleGroup\\n description\\n backgroundColors\\n layout\\n link {\\n src\\n linkText\\n }\\n image {\\n src\\n alt\\n }\\n }\\n ... on StorefrontFreeGames {\\n type\\n title\\n }\\n ... on StorefrontCardGroup {\\n type\\n title\\n link {\\n src\\n linkText\\n }\\n offers {\\n namespace\\n id\\n offer {\\n \\n title\\n id\\n namespace\\n description\\n keyImages {\\n type\\n url\\n }\\n seller {\\n id\\n name\\n }\\n urlSlug\\n items {\\n id\\n namespace\\n }\\n customAttributes {\\n key\\n value\\n }\\n categories {\\n path\\n }\\n price(country: $country) {\\n totalPrice {\\n discountPrice\\n originalPrice\\n voucherDiscount\\n discount\\n fmtPrice(locale: $locale) {\\n originalPrice\\n discountPrice\\n intermediatePrice\\n }\\n }\\n lineOffers {\\n appliedRules {\\n id\\n endDate\\n }\\n }\\n }\\n linkedOfferId\\n linkedOffer {\\n effectiveDate\\n customAttributes {\\n key\\n value\\n }\\n }\\n \\n }\\n }\\n }\\n ... on StorefrontFeaturedCarousel {\\n type\\n title\\n slides {\\n title\\n eyebrow\\n description\\n backgroundColor\\n image {\\n src\\n alt\\n }\\n mobileImage {\\n src\\n alt\\n }\\n link {\\n src\\n linkText\\n }\\n }\\n }\\n ... on StorefrontTiles {\\n type\\n title\\n tiles {\\n label\\n genre\\n link {\\n src\\n linkText\\n }\\n }\\n }\\n }\\n }\\n }\\n ","variables":{"locale":"ru-RUS","country":"RUS"}}'
data = requests.post(endpoint, headers={"Content-type": "application/json;charset=UTF-8"
}, data=query)
data = data.json()
print('Games:')
for slides in data['data']['Storefront']['storefrontModules']: #Перебирае категории игр (На распродажах, бесплатные игры и т.д.)
if len(slides) > 0:
try: # Проверяем если в категории игры
for game in slides['offers']:
print(game['offer']['title']) # Если есть то выводим
except:
pass
Попробуй отследить запрос который посылает сам сайт серверу, скопировать curl и вставить его https://curl.trillworks.com
Даст тебе подробный запрос с куками хедером и параметрами в валидном виде