Не получается спарсить все страницы. Парсится только первая
Недавно начал изучать парсиниг. Пытаюсь спарсить сайт. Возникает проблема, не меняется номер страницы и парсится первая страница по кругу. Предполагаю что проблема в строке:
html = get_html(URL, params={'page/': page})
однако не могу придумать как её в данном случае переписать.
import requests
from bs4 import BeautifulSoup
import csv
URL = 'https://app2top.ru/page/1?s=game+insight''
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
'accept': '*/*'}
FILE = 'articles.csv'
def get_html(URL, params=None):
r = requests.get(URL, headers=HEADERS, params=params)
return r
def get_pages_count(html):
soup = BeautifulSoup(html, 'html.parser')
pagination = soup.find_all('a', class_='page-numbers')
return int(pagination[-2].get_text())
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.findAll('article', class_='preview preview_news')
articles = []
for item in items:
articles.append({
'title': item.find('h2', class_='preview__content_title').get_text(),
'link': item.find('a', class_='meta__comments').get('href', ).rstrip('/#comments')
})
return articles
def save_file(articles, path):
with open(path, 'w', newline='') as file:
writter = csv.writer(file, delimiter=';')
writter.writerow(['Название статьи', 'Ссылка'])
for item in articles:
writter.writerow([item['title'], item['link']])
def parse():
html = get_html(URL)
if html.status_code == 200:
articles = []
pages_count = get_pages_count(html.text)
for page in range(1, pages_count + 1):
print(f'Парсится {page} страница из {pages_count}... {URL}')
html = get_html(URL, params={'page/': page})
articles.extend(get_content(html.text))
save_file(articles, FILE)
print(f' Найдено {len(articles)} статей')
print('Файл сохранен')
else:
print('Error')
parse()