天天看点

链家爬虫2019

环境:win10 +python3.6 +pycharm 2018

代码如下:

# coding=utf-8
import requests
from parsel import Selector
import pandas as pd
import time
from lxml import etree
import re
#############################################################
'''
爬取链家网海淀区的二手房信息
@time=2019-6-5
@author=yys
'''
###########################################################
# 进行网络请求的浏览器头部
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 BIDUBrowser/8.7 Safari/537.36'

}
# pages是不同页码的网址列表
pages = ['https://bj.lianjia.com/ershoufang/haidian/pg{}/'.format(x) for x in range(1,100)]
############################################################

#############################################################
lj = pd.DataFrame(columns=['地区', '小区', '总价','单价','房间数','面积','朝向','是否精装',"电梯",'楼层','年龄'])
count = 0
def get_page(url):
    # 这个函数是用来获取链家网海淀区二手房的信息
    wr = requests.get(url, headers=headers, stream=True)
    sel=etree.HTML(wr.text)
    # describ = sel.xpath('//li[@class="clear LOGCLICKDATA"]/div[@class="houseInfo"]')
    neighbor = sel.xpath('//li[@class="clear LOGCLICKDATA"]//div[@class="houseInfo"]/a/text()')#所在小区
    total=sel.xpath('//li[@class="clear LOGCLICKDATA"]//div[@class="houseInfo"]/text()')
    total2=sel.xpath('//li[@class="clear LOGCLICKDATA"]//div[@class="positionInfo"]/text()')
    district=sel.xpath('//li[@class="clear LOGCLICKDATA"]//div[@class="positionInfo"]/a/text()')
    price=sel.xpath('//li[@class="clear LOGCLICKDATA"]//div[@class="priceInfo"]/div[@class="totalPrice"]/span/text()')
    unit_price=sel.xpath('//li[@class="clear LOGCLICKDATA"]//div[@class="priceInfo"]/div[@class="unitPrice"]/span/text()')
    # total_str='+'.join(total)
    # room1=re.findall('\d室\d厅',total_str)
    # mianji=re.findall("\d*.\d*平米",total_str)
    # dianti=re.findall('.电梯',total_str)
    # print(total_str)
    # print(dianti)
    room=total[0::5]
    area=total[1::5] #面积
    orien=total[2::5] #朝向
    nice=total[3::5]#是否精装
    elevator=total[4::5]
    floor=total2[0::2]
    years=total2[1::2]
    pages_info = pd.DataFrame(list(zip(district,neighbor,price,unit_price,room,area,orien,nice,elevator,floor,years)), columns=['地区', '小区', '总价','单价','房间数','面积','朝向','是否精装',"电梯",'楼层','年龄'])
    return pages_info
for page in pages:
    a = get_page(page)
    count = count + 1
    print('the ' + str(count) + ' page is sucessful')
    time.sleep(5)
    lj_futian = pd.concat([lj, a], ignore_index=True)
# 将表格数据输出到excel文件
lj.to_excel('d:\\链家_海淀.xlsx')
           

存在的问题

由于网站本身有些内容放置的顺序有些混乱,导致最终生成的excel表部分行单元对不上列名。

可以使用正则表达式来细划分。

链家爬虫2019

结果

链家爬虫2019

下载地址

海淀_链家_爬虫数据.xlsx

个人总结

1.使用{}+format+列表推导完成爬虫网页列表的构造。

2.使用request+xpath可以完成大多数简单网页数据的爬取,对于格式混乱的数据可以使用正则表达式来进行精确爬取。