jeudi 20 juin 2019

How to scrap information from a website and skip to the next point if the information is not existing

I want to scrape information from a real estate website for market research purpose. My problem right now is that if some house doesn`t have all the information i want (e.g. the markler didnt put the size of house in his exposé) then the script stops and i get an error.

I already tried it with If-/Else Statements but i make some mistake that it doesnt work like this. But i get the Error: "UnboundLocalError: local variable 'Flattyp' referenced before assignment"

def get_house_info (House):
    for id in ids:
            sourceCode = urllib.request.urlopen('https://www.immobilienscout24.de/expose/' + str(id)).read()
            purchasePrice = str(sourceCode).split('"purchasePrice":')[1].split(',"geoCode"')[0]
            Spacesize = str(sourceCode).split('"area":')[1].split('},"details"')[0]
            District = str(sourceCode).split('"quarter":')[1].split('},')[0]
            if Flattyp != str(sourceCode).split('"is24qa-typ grid-item three-fifths">')[1].split('</dd> </dl> <dl class')[0]:
                Flattyp = "nicht vorhanden"
            else:
                Flattyp = str(sourceCode).split('"is24qa-typ grid-item three-fifths">')[1].split('</dd> </dl> <dl class')[0]
            Rooms = str(sourceCode).split('is24qa-zimmer grid-item three-fifths"> ')[1].split(' </dd> </dl> <dl class=')[0]
            parking_space = str(sourceCode).split('<dd class="is24qa-garage-stellplatz grid-item three-fifths">')[1].split('</dd> </dl>')[0]
            if parking_space != str(sourceCode).split('<dd class="is24qa-garage-stellplatz grid-item three-fifths">')[1].split('</dd> </dl>')[0]:
                parking_space = "nicht vorhanden"
            else: 
                parking_space = str(sourceCode).split('<dd class="is24qa-garage-stellplatz grid-item three-fifths">')[1].split('</dd> </dl>')[0]

            with open('fooneu23.txt', 'a') as csvfile:
                cols = ['id', 'price', 'size', 'district', 'flattyp', 'rooms', 'parking_space','Flattypp']
                dict_result = {'id': id, 'price': purchasePrice, 'size': Spacesize, 'district': District, 'flattyp': Flattyp, 'rooms': Rooms, 'parking_space':parking_space, 'Flattypp':Flattypp}
                writer = csv.DictWriter(csvfile, fieldnames=cols)
                writer.writeheader()
                writer.writerow(dict_result)

            csvfile.close()

Aucun commentaire:

Enregistrer un commentaire