[英]How to scrape information from a website and skip to the next point if the information is not existing
我想從房地產網站上抓取信息以進行市場研究。 我現在的問題是,如果某些房子沒有我想要的所有信息(例如,房地產經紀人沒有將房子的大小放在他的曝光中),那么腳本就會停止,我會收到錯誤消息。
我已經用if
/ else
語句試過了,但我犯了一些錯誤,所以它不能像這樣工作。 我收到錯誤:
“UnboundLocalError:賦值前引用了局部變量‘Flattyp’”
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()
錯誤在這里:
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]
在第一次迭代時,您將Flattyp
與某物進行比較,但尚未設置Flattyp
。
對於您最初的問題,您聽說過try/catch語句嗎?
您應該對請求的所有響應進行一次解碼,而不是多次將其轉換為字符串:
sourceCode = urllib.request.urlopen(
'https://www.immobilienscout24.de/expose/' + str(id)
).read().decode('utf8')
最后,永遠不要使用 str 函數(regexp、split)來解析 html。 使用合適的 html 解析器,比如beautifulsoup 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.