S
S
s19s932021-08-13 15:38:29
Python
s19s93, 2021-08-13 15:38:29

Error writing to txt?

I want to transfer data to be written to a txt file.
I pass an argument to the function, but for some reason it swears, where am I stupid?

from bs4 import BeautifulSoup
import requests


def save(i):
    with open ('parse_info.txt', 'a') as file:
        file.write(f'{i["title"]} -> {i["price"]}')


def parse():
    url = "https://www.avito.ru/kaliningrad/zemelnye_uchastki?cd=1"
    headers = {
        'User-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"
    }

    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')
    title = soup.findAll('div', class_='iva-item-root-G3n7v photo-slider-slider-3tEix iva-item-list-2_PpT iva-item-redesign-1OBTh items-item-1Hoqq items-listItem-11orH js-catalog-item-enum')
    list_1 = []
    # Цикл названия
    for item in title:
            list_1.append(
            {
                'title': item.find('h3', class_="title-root-395AQ iva-item-title-1Rmmj title-listRedesign-3RaU2 title-root_maxHeight-3obWc text-text-1PdBw text-size-s-1PUdo text-bold-3R9dt").get_text(strip = True),
                'price':item.find('span',class_="price-text-1HrJ_ text-text-1PdBw text-size-s-1PUdo").get_text(strip = True)     
            } 
        )

    for i in list_1:
        print(i['title'])
        print(i['price']) 
        save()


parse()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alexbprofit, 2021-08-13
@alexbprofit

for i in list_1:
        print(i['title'])
        print(i['price']) 
        save(i)

S
soremix, 2021-08-13
@SoreMix

1. You don’t pass anything to it, save(i)
2. You f'{i["title"]} -> {i["price"]}'need to add a hyphen to it, otherwise everything will stick together:
f'{i["title"]} -> {i["price"]}\n'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question