1. 程式人生 > 其它 >爬取某房源網資料 - Python

爬取某房源網資料 - Python

爬取某房源資料,算加深對parsel庫的使用。

 1 """
 2     爬取房源
 3 """
 4 
 5 import requests
 6 import csv
 7 import parsel
 8 
 9 # 請求頭
10 headers = {
11     'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
12 }
13 # 要請求的地址
14 url = 'https://xx.newhouse.xx.com/house/s/
' 15 16 # 請求後返回的狀態碼 17 response = requests.get(url, headers=headers) 18 19 # 開始解析資料 20 selector = parsel.Selector(response.text) 21 22 # 找到所有li標籤 23 lis = selector.xpath('//div[@class="nl_con clearfix"]/ul/li[not(@style)]') # 取頁面中所有的li標籤,但是不要包含li有style屬性的那行 24 25 # 開始迴圈 26 for li in lis: 27 name = li.xpath('
.//div[@class="nlcd_name"]/a/text()').get() # 提取名稱.表示當前節點 28 # 但是發現很多空白,假定這個name都有值 29 if name: 30 name = name.strip() # 去除左右兩邊的空白 31 price = li.xpath('.//div[@class="nhouse_price"]/*/text()').getall() # 價格 32 if price: 33 price = ''.join(price) # 將價格轉換成字串 34 else: 35 price = '
暫未取得預售證!' 36 37 room = li.xpath('.//div[@class="house_type clearfix"]/a/text()').getall() # 幾居室 38 if room: 39 room = '/'.join(room) 40 else: 41 room = '未知!' 42 43 area = li.xpath('.//div[@class="house_type clearfix"]/text()').re('[\d~平米]+') 44 if area: # 可能會存沒有值的情況 45 area = area[0] 46 else: 47 area = '未知' 48 address = li.xpath('.//div[@class="address"]/a/@title').get() # 地址 49 sale = li.xpath('.//div[@class="fangyuan"]/span/text()').get().strip() # 是否在售 50 tel = li.xpath('.//div[@class="tel"]/p/text()').getall() # 電話聯絡方式 51 if tel: 52 tel = ''.join(tel) 53 else: 54 tel = '電話號碼未知!' 55 detailPage = li.xpath('.//div[@class="nlcd_name"]/a/@href').get() 56 print(name, price, room, area, address, sale, tel, detailPage, sep='---') 57 58 # 開始儲存資料 59 with open('謀天下房源.csv', mode='a', encoding='utf-8-sig', newline='') as f: # 不加newline的話會有空行,後面的''表示消除空行 60 csvWriter = csv.writer(f) # 例項化一個物件 61 csvWriter.writerow([name, price, room, area, address, sale, tel, detailPage]) #把列表按一行一行寫入