1. 程式人生 > >利用高德API + Python爬取鏈家網租房資訊 01

利用高德API + Python爬取鏈家網租房資訊 01

看了實驗樓的專案發現五八同城爬取還是有點難度所以轉戰鏈家


實驗程式碼如下


from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv

url = 'https://gz.lianjia.com/zufang/rs{page}/'

page = 0

csv_file = open('fang.csv','w')
#這裡open開啟需要‘w’不要‘wb’,使用‘wb’會出現一下錯誤:
#TypeError: a bytes-like object is required, not 'str'


csv_write = csv.writer(csv_file,delimiter=',')

while True:
    page += 1
    print('正在下載網頁:',url.format(page=page))
    respone = urlopen(url.format(page=page))
    html = BeautifulSoup(respone)    
    house_list = html.find('div',class_='list-wrap').find_all('div',class_="info-panel")
    #採用先取大後取小的原則
    #這裡提取記得爬取有用的,在這我是提取‘info-panel’這的
    
    

    for house in house_list:
        house_title = house.find('a',target='_blank').get_text()
        house_url = house.find('div',class_='where').a['href']
        house_money = house.find('div',class_='price').span.get_text()
        house_location = house.find('div',class_='con').a.get_text()
        csv_write.writerow([house_title,house_location,house_money,house_url])
        
    

csv_file.close()    

這個程式碼並不完善爬取10頁就會出現 HTTPError: Not Found

明顯的網站對IP的限制,下一步我將完善程式碼進行IP代理池以及請求的設定