0
我已經定義了一個從網頁中抓取數據的函數。在這個網頁上有25個搜索結果(在我的案例中屬性列表)。我編寫了代碼來查找所有這些列表中的25個,然後嘗試使用for循環在網頁上的每個列表中調用我的函數。但是,輸出顯示同一列表打印了25次。我想知道是否有可能將我的功能details()
應用到找到的所有25個房源列表中:listings = soup.find_all('article',{'role' : 'article'})
。然後我需要將這些結果輸出到CSV文件中。Python函數輸出重複值
我使用Python 2.7
這是我到目前爲止有:
output = []
property = []
def address():
for address in soup.find('span', {'itemprop' : 'address'}):
property.append(address.text)
def sqft():
for sqft in soup.find('dl',{'class' : 'property-info-sheet pier-5'}):
property.append(sqft.text)
def lot():
for lot in soup.find('dl',{'class' : 'property-info-sheet pier-6'}):
property.append(lot.text)
def built():
for built in soup.find('dl',{'class' : 'property-info-sheet pier-7'}):
property.append(built.text)
def details():
address()
sqft()
lot()
built()
file = 'output.csv'
with open(file,'wb') as f:
writer = csv.writer(f)
writer.writerow(property)
listings = soup.find_all('article',{'role' : 'article'})
for listing in listings:
details()
這25次輸出相同的上市。是否有可能每次上市一次而不是一次上市25次?
我不會跟隨此。如果我將詳細信息發送到詳細信息(詳細信息(列表)),則循環以錯誤結束:'Nonetype'對象不可迭代。 – Steve
現在,您可以使用BeautifulSoup解析骯髒的部分。返回的值有各種類型,包括可能的無。在這裏查找是爲了返回一個單一的值,但你正在迭代它。這對一些類型是可能的,但對其他類型是可能的我建議擺脫for循環或切換到find_all。 –
好的,謝謝你的幫助! – Steve