【要爬取的數據來源】
?在列表頁爬取詳細介紹的網址
?在詳細介紹爬取房源具體信息:
標題、地址、價格、第一幅圖片、房主姓名、性別、頭像
列表頁
詳情頁
【成果(將其輸出到TXT文件中了)】
1
2
【代碼】
from bs4 import BeautifulSoup
import requests
import time
#一共13頁房源信息
list_urls = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(i) for i in range(1, 14)]
#此函數用于判斷房主性別
def sexual(sex):
if sex == ['member_ico']:
return 'male'
elif sex == ['member_ico1']:
return 'female'
else:
return 'unknown'
#此函數用于獲取列表頁的24個詳情頁地址,返回值為一個列表
def getList (list_url):
respond = requests.get(list_url)
wb_data = BeautifulSoup(respond.text, 'lxml')
get_urls = wb_data.select('#page_list > ul > li > a')
urls = []
for a_url in get_urls:
url = a_url.get('href')
urls.append(url)
return urls
#此函數用于獲取詳情頁的各種信息,返回值為一個字典
def getDetail(url):
respond = requests.get(url)
wb_data = BeautifulSoup(respond.text, 'lxml')
titles = wb_data.select('body > div.wrap.clearfix.con_bg > div.con_l > div.pho_info > h4 > em')
positions = wb_data.select('body > div.wrap.clearfix.con_bg > div.con_l > div.pho_info > p > span.pr5')
prices = wb_data.select('#pricePart > div.day_l > span')
images = wb_data.select('#detailImageBox > div.pho_show_l > div > div:nth-of-type(2) > img')
names = wb_data.select('#floatRightBox > div.js_box.clearfix > div.w_240 > h6 > a')
host_images = wb_data.select('#floatRightBox > div.js_box.clearfix > div.member_pic > a > img')
sexs = wb_data.select('#floatRightBox > div.js_box.clearfix > div.member_pic > div')
for title, position, price, image, name, host_image, sex in zip(titles, positions, prices, images, names, host_images,
sexs):
detail = {
'title': title.get_text(),
'position': position.get_text().replace('\n ', ''),
'price': price.get_text(),
'image': image.get('src'),
'name': name.get_text(),
'host_image': host_image.get('src'),
'sex': sexual(sex.get('class'))
}
return detail
#用于放置300個房源地址的列表
urls = []
#每獲取24個房源地址,若列表小于300,則把該地址放入列表中
for list_url in list_urls:
time.sleep(2)
urls1 = getList (list_url)
for urls2 in urls1:
if len(urls) < 300:
urls.append(urls2)
print(len(urls))
#輸出300個地址
print(urls)
#打開一個文件,續寫模式
path = 'C:/Users/Administrator/DeskTop/sores.txt'
file = open(path,'a')
#計算該房源是第幾個房
count = 0
#開始爬取和輸出300個房源的具體信息
for url in urls:
count = count + 1
if count % 3 == 0:#判斷進度
print (count/3,'%')
file.write('\n\ncount = '+ str(count) +'\n')
time.sleep(2)
file.write(str(getDetail(url)))
file.close()
print('down')
#結束
【debug日記~】
通過select和get('class')過濾得到的性別其實是一個列表,一開始用字符串來判斷總是跳到else,而且ico1那個1是數字1而不是英文字母l
輪播圖其實有用到js進行控制,所以沒辦法直接取到圖片的selector,但是可以從父級地址中自己添加一個> img 來獲取第一張圖的地址
一開始取不到頭像地址還以為怎么了,換了手機端的header還是不行,結果是忘記寫select(蠢到家……)
借助sleep來延遲爬取時間進行保護確實很慢,要學學看新的辦法才行
一個比較基礎的問題,write只能寫入字符串,所以要把字典轉換成字符串才行(強制轉化還真是好方便,life is short,you need python)
User-Agent中間的不是下劃線!
找唯一特征時(這次因為每個元素都是單一的所以沒怎么用到),一般用.來定位class,用[]來定位屬性
愉快地結束了!(一個小tips,如果按照教程總是爬不到所需要的信息,可以留意看看respond的網頁內容是不是有所更改~)