0

Парсит Avito , но постоянно повторяет одни и те же данные

Вот как должно выглядеть:

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/kompyuter_1862746379

Системный блок на LGA 2011 <--> Цена: 28 000 ₽ <--> Район: р-н Кировский <--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/sistemnyy_blok_na_lga_2011_1437704393

Системный блок <--> Цена: 2 500 ₽ <--> Район: р-н Советский
<--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/sistemnyy_blok_1946323404

Игровой Системный блок <--> Цена: 43 500 ₽ <--> Район: р-н Кировский <--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/igrovoy_sistemnyy_blok_1938193100

А вот как отображает:

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/kompyuter_1862746379

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/kompyuter_1862746379

Системный блок на LGA 2011 <--> Цена: 28 000 ₽ <--> Район: р-н Кировский <--> Ссылка: https://www.avito.ru//astrahan/nastolnye_kompyutery/sistemnyy_blok_na_lga_2011_1437704393

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<-->

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<-->

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<-->

Системный блок на LGA 2011 <--> Цена: 28 000 ₽ <--> Район: р-н Кировский <-->

Компьютер <--> Цена: 5 000 ₽ <--> Район: р-н Трусовский
<-->

Системный блок на LGA 2011 <--> Цена: 28 000 ₽ <--> Район: р-н Кировский <-->

Вот код:

import requests
from bs4 import BeautifulSoup as BS
import time 

def save():
    with open ('parse_info.txt', 'a', encoding='utf-8') as file:
        file.write(f'{comp["title"]}   <-->   Цена: {comp["price"]}   <-->   Район: {comp["place"]}   <-->   Ссылка: https://www.avito.ru/{comp["link"]}\n\n')

def parse():

URL = ''    
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
}

response = requests.get(URL)
soup = BS(response.content, 'html.parser')
items = soup.findAll('div', class_ = 'description item_table-description')
comps = []

for item in items:
    comps.append({
        'title': item.find('a', class_ = 'snippet-link').get_text(strip = True),
        'price': item.find('span', class_ = 'snippet-price').get_text(strip = True),
        'link': item.find('a', class_ = 'snippet-link').get('href'),
        'place': item.find('span', class_ = 'item-address-georeferences-item__content').get_text(strip = True)
        })

    global comp

    for comp in comps:
        print(f'{comp["title"]}   <-->   Цена: {comp["price"]}   <-->   Район: {comp["place"]}   <-->   Ссылка: {comp["link"]}\n')
        time.sleep(3)
        save()

parse()

1 ответ 1

1

К приведенному вами коду много вопросов. Например, зачем вам global comp? Или time.sleep(3)?

Полагаю, что проблема в отступах. Цикл for item in items каждую итерацию выполняет вложенный цикл for comp in comps. Сюда накладываются непонятные махинации с глобальным доступом и таймером.

Код ниже пишет в файл после парса всех данных. В ходе написания возникла ошибка. Значение place может содержаться как в span с классом item-address-georeferences-item__content, так и item-address__string

import requests
from bs4 import BeautifulSoup as BS

def save(comps):
    with open ('parse_info.txt', 'a', encoding='utf-8') as file:
        for comp in comps:
            file.write(f'{comp["title"]}   <-->   Цена: {comp["price"]}   <-->   Район: {comp["place"]}   <-->   Ссылка: https://www.avito.ru/{comp["link"]}\n\n')

def parse(url):
    response = requests.get(url)
    soup = BS(response.text, 'html.parser')
    items = soup.findAll('div', class_ = 'item_table-description')

    comps = []
    for item in items:
        place =  item.find('span', class_ = 'item-address-georeferences-item__content')
        if not place:
            place = item.find('span', class_ = 'item-address__string')

        comps.append({
            'title': item.find('a', class_ = 'snippet-link').get_text(strip = True),
            'price': item.find('span', class_ = 'snippet-price').get_text(strip = True),
            'link': item.find('a', class_ = 'snippet-link').get('href'),
            'place': place.get_text(strip = True)
        })

    return comps

url = 'https://www.avito.ru/astrahan/nastolnye_kompyutery'    
save(parse(url))

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.