2016-04-05 94 views
2

我試圖爲流行的汽車網站建立一個快速刮板。我可以得到一輛車的結果,但我不知道如何返回頁面上的所有汽車。 findAll()正在拋出一個錯誤。任何幫助,將不勝感激迭代通過頁面元素beautifulsoup

from bs4 import BeautifulSoup 
import requests 

#search = input('Enter car to search: ') 
url = 'https://www.donedeal.ie/cars?words=bmw' #+ search 
site = requests.get(url) 
page = site.content 
soup = BeautifulSoup(page, 'html.parser') 
print("URL: ", site.url) 

if site.status_code == 200: 
    print("HTTP Status: ", site.status_code, "\n") 
else: 
    print("Bad HTTP response", "\n") 

cars = soup.find('div', attrs={'class': 'top-info'}) 
county = soup.find('span', attrs={'class': 'county-disp icon-pin'}) 
span = cars.find('span') 

for result in span: 
    for result2 in county: 
     print(result, "-", result2) 
+1

您的示例中沒有使用findAll()。另外:拋出什麼錯誤? – vds

+0

上面的代碼中沒有引發錯誤,代碼只返回一個值。 –

回答

2

我不知道你想提取哪些信息。假設您想要的車型和縣信息,findAll()作品像這樣的東西:

>>> cars = soup.findAll('div', attrs={'class': 'top-info'}) 
>>> for car in cars: 
...  loc = car.find('span', attrs={'class': 'county-disp icon-pin'}) 
...  if loc: 
...   print('type:', car.text, 'location:', loc.text) 
...  else: 
...   print('type:', car.text) 
type: Bmw 320 CdTipperary location: Tipperary 
type: Bmw 520d MsportDonegal location: Donegal 
type: BMW2004 
type: BMW2010 
type: Bmw2010 
type: Bmw2000 
type: Bmw2001 
type: Bmw2004 
type: Bmw2004 
type: bmw2003 
type: BMW2009 
type: Bmw2010 
type: Bmw1990 
type: BMW2004 
type: BMW2012 
type: Bmw2000 
type: bmw2001 
type: BMW2004 
type: BMW2008 
type: BMW2005 
type: Bmw2006 
type: Bmw2002 
type: BMW2004 
type: Bmw2000 
type: BMW2003 
type: BMW2011 
type: BMW2001 
type: Bmw2000 
type: Bmw2002 
type: BMW2007 

請注意:一個頁面而已。你將不得不做其他頁面的網址。