網絡爬蟲實戰2-365淘房網二手房信息爬取(04)
摘要:本文抓取,365淘房網,弋江區二手房信息,包含信息名稱,小區信息,板塊區域,總價,單價等,并作為csv文件輸入。
00 HTML文件分析
需要爬取的信息都在這里;

打開第一個標記<div>,需要爬取的信息在這里;

01 導入所需庫,建立空列表放置爬取信息,定義請求頭
import requests
import chardet
from bs4 import BeautifulSoup
import numpy as np
title=[] #標題
address1=[] # 房產信息
address2=[] #房產信息
content1=[] # 小區名稱
content2=[] # 所屬板塊
price1=[] #總價
price2=[] #單價
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0)\
Gecko/20100101 Firefox/47.0'} #\為換行符
02 爬取前五頁的相關信息
for i in range(1,6):
link='http://wh.sell.house365.com/district_d3/dl_x1-p'+str(i)+'.html'
res=requests.get(link,headers=headers,timeout=10)
res.encoding=chardet.detect(res.content)['encoding']
soup=BeautifulSoup(res.text,'lxml')
houselist=soup.find_all('div',class_='listItem__info')
for house in houselist:
title.append(house.h2.a.div.string.strip())
address1.append(house.find('p',class_='listItem__address').contents[1].string.strip())
address2.append(house.find('p',class_='listItem__address').contents[3].string.strip())
content1.append(house.find('p',class_='listItem__content').contents[1].a.string.strip())
content2.append(house.find('p',class_='listItem__content').contents[3].string.strip())
price1.append(house.find('div',class_='listItem__price').span.string.strip())
price2.append(house.find('div',class_='listItem__price').div.string.strip())
03 總價列表只有數字,沒有單位,需要加上單位‘萬元’
for j in range(100):
price1[j]=price1[j]+'萬元'
04 把所有信息綜合成一個二維數組
yjf=np.array([title,address1,address2,content1,content2,price1,price2]) 
05 輸出到CSV文件
import csv
csvobj=open('yjf.csv','w',newline='',encoding='GB2312')
csvfile=csv.writer(csvobj)
csvfile.writerow(title)
csvfile.writerow(address1)
csvfile.writerow(address2)
csvfile.writerow(content1)
csvfile.writerow(content2)
csvfile.writerow(price1)
csvfile.writerow(price2)
csvobj.close()

工程師必備
- 項目客服
- 培訓客服
- 平臺客服
TOP




















