Не отображаются данные при реализации парсинга Python
заинтересовался идеей парсинга на Python.Суть такова , нужно получить информацию : Цена , название и ссылка с сайта https://matraster.ru/matrasy-ceny/
Написал вот такой код
import requests
def save():
with open('parse_info.txt', 'w') as file:
file.write(f"{comp['title']} -> Price: {comp['price']} -> Link: {comp['link']}\n")
def parse():
URL = 'https://matraster.ru/matrasy-ceny/'
HEADERS = {
'User-Agent': 'Тут он есть'
}
response = requests.get(URL, headers = HEADERS)
soup = BeautifulSoup(response.content, 'html.parser')
items = soup.findAll('div', class_ = 'flex product')
comps = []
for item in items:
comps.append({
'title': item.find('div', class_ = 'name').get_text(strip = True),
'price': item.find('div', class_ = 'price').get_text(strip = True),
'link': item.find('div', class_ = 'name').get('href')
})
global comp
for comp in comps:
print(f"{comp['title']} -> Price: {comp['price']} -> Link: {comp['link']}")
save()
parse()
При выполнении через командную строку (от имени администратора) не происходит создания файла , если же убрать функцию сохранения и просто вывести всю информацию через командную строку , то там нет никакой информации.
Ответы (1 шт):
Автор решения: Jack_oS
→ Ссылка
Вы искали немного не в тех классах, но в целом - хорошая попытка для первого раза!
Переделал немного ваш код с учетом ошибок:
import requests
from bs4 import BeautifulSoup
URL = 'https://matraster.ru/matrasy-ceny/'
HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}
def parse():
response = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(response.content, 'html.parser')
items = soup.find_all('div', class_='item product_item')
mattress_list = []
for item in items[3:-1]:
title_raw = item.find('div', class_='name')
name = title_raw.find('a').contents[0]
link = title_raw.find('a')['href']
current_price = item.find('div', class_='price').find('div').get_text(strip=True)
mattress_list.append({
'title': name,
'price': current_price.replace('р.', '').replace(' ', ''),
'link': link
})
return mattress_list
def save(items):
with open('parse_info.txt', 'w') as file:
for item in items:
file.write(f"{item['title']} -> Price: {item['price']} -> Link: {item['link']}\n")
save(parse())
В parse_info.txt записывает товары с первой страницы.