第二章 爬取案例-链家租房数据获取 2021-09-16

爬虫系列总目录

本章节介绍爬虫中使用的基础库用于选择,过滤页面信息。包括requests,bs4,xpath,正则表达式re,json 等内容,能够实现对简单页面的获取。
第二章 爬虫基础库-requests/bs4
第二章 正则表达式
第二章 简单网页的爬取与Xpath、Json使用
第二章 页面爬取应用-缺失数据处理、图片下载、懒加载
第二章 爬取案例-链家租房数据获取


一、 需求描述

获取某一城市下的租房信息,房源名称,位置,面积,朝向,户型,租金等信息,保存到Excel中,并且保存详情页中的图片。

分析: 租房信息中无相关接口返回的数据,通过Xpath 获取到页面信息。
控制爬取速度,防止过多请求造成的服务器压力过大,以及验证码等相关反爬虫机制。

二、代码结构

def main(num, path, temp_url):
    """
    主函数
    """
    # 获取要爬取的网页,网页特点决定,按页来遍历
    target_url = get_url(num, temp_url)
    # 结果变量
    all_info = {'房源名称': [], '位置': [], '面积': [], '朝向': [], '户型': [], '租金': [], 'next_url': []}
    for i, url in enumerate(target_url):
    	# 获取响应
        response = get_response(url)
        # 处理响应到变量中
        all_info = get_info(response.text, all_info)
    # 保存图片数据
    get_img_and_download(imge_urls, house_name, path)
    # 保存数据到Excel中
    save_data(path, all_info)
    


if __name__ == '__main__':
    temp_url = 'https://bj.lianjia.com/zufang/pg{}'
    path = './lianjia'
    num = input('爬取的⻚数:')
    if num.isdigit():
        num = int(num)
        print(main(num, path, temp_url))
    else:
        print('num输⼊的不是纯数字')

三、代码总结

3.1 根据charset 自动设置编码

response.encoding = response.apparent_encoding

3.2 数据获取

3.2.1数据的一次性获取后处理

数据特点使用 / 分割,使用Xpath(“string()”) 获取当前标签下的所有文本内容。
在这里插入图片描述

def get_info(response, all_info):
    """
    获取响应解析,保存数据到all_info中
    """
    etree_html = etree.HTML(response, etree.HTMLParser())
    titles = etree_html.xpath("//div[@class='content__list--item--main']/p[1]/a/text()")
    all_info['房源名称'].extend(list(map(lambda x: x.strip(), titles)))
    sub_title = etree_html.xpath("//div[@class='content__list--item']/div")
    for info in sub_title:
        sub_results = info.xpath("string(./p[2])").split("/")
        all_info["位置"].append(sub_results[0].strip())
        all_info["面积"].append(sub_results[1].strip())
        all_info["朝向"].append(sub_results[2].strip())
        all_info["户型"].append(sub_results[3].strip())
        all_info["租金"].append(info.xpath("string(./span)").strip())
    return all_info

3.2.2 图片懒加载的获取

获取的src 数据为data-src, src 是拿不到真实的图片地址。

        download_urls = img_html.xpath("//div[@class='content__article__slide__item']/img/@data-src")

3.2.3 获取路径中包含/, 保存时被当成子文件夹处理

四、 示例代码

优化方向:
1、能控制 get_response 方法请求不要太快,保存上次请求时间,若时间过短则sleep。
2、将缺失的图片的页面输出到结果中,而不是直接print
3、爬取速度较慢,增加请求速度同时不被识别。

import requests
from lxml import etree
import time
import random
import os
import pandas

def get_info(response, all_info):
    """
    获取响应解析,保存数据到all_info中
    """
    etree_html = etree.HTML(response, etree.HTMLParser())
    titles = etree_html.xpath("//div[@class='content__list--item--main']/p[1]/a/text()")
    all_info['房源名称'].extend(list(map(lambda x: x.strip(), titles)))
    sub_title = etree_html.xpath("//div[@class='content__list--item']/div")
    for info in sub_title:
        sub_results = info.xpath("string(./p[2])").split("/")
        all_info["位置"].append(sub_results[0].strip())
        all_info["面积"].append(sub_results[1].strip())
        all_info["朝向"].append(sub_results[2].strip())
        all_info["户型"].append(sub_results[3].strip())
        all_info["租金"].append(info.xpath("string(./span)").strip())
    all_info['next_url'].extend(etree_html.xpath("//div[@class='content__list--item']/a/@href"))
    return all_info

def get_url(num, temp_url):
    """
    拼接url,并且返回
    """
    urls = [temp_url.format(i) for i in range(1, num + 1)]
    return urls


def get_response(url, headers=None):
    """
    获取url对应响应
    """
    if headers is None:
        _headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
        }
    response = requests.get(url, headers=_headers)
    response.encoding = response.apparent_encoding
    return response


def get_img_and_download(urls, house_name, path, headers=None):
    no_img = 'https://image1.ljcdn.com/rent-front-image/2a778015dbbab30fcde0a978314ce007.png.780x439.jpg'

    for i, img_url in enumerate(urls):
        img_response = get_response(img_url)
        img_html = etree.HTML(img_response.text, etree.HTMLParser())
        # image_name = img_html.xpath("string(//div[@class='content clear w1150']/p)").strip()
        image_name = house_name[i]

        image_dir = os.path.join(path, image_name.replace("/", "-"))

        download_urls = img_html.xpath("//div[@class='content__article__slide__item']/img/@data-src")
        if len(download_urls) == 1 and download_urls[0] == no_img:
            print('{}没有图片, html: {}'.format(image_name, img_url))
            continue

        if not os.path.exists(image_dir):
            os.makedirs(image_dir)

        for j, download_url in enumerate(download_urls):
            with open(os.path.join(image_dir, '{}_{}.jpg'.format(image_name,j)), 'wb') as f:
                f.write(get_response(download_url, headers=headers).content)


def save_data(path, all_info):
    df_data = pandas.DataFrame(all_info)
    df_data.to_excel(os.path.join(path, "result.xlsx"))


def main(num, path, temp_url):
    """
    主函数
    """
    target_url = get_url(num, temp_url)
    # 结果变量
    all_info = {'房源名称': [], '位置': [], '面积': [], '朝向': [], '户型': [], '租金': [], 'next_url': []}
    for i, url in enumerate(target_url):
        response = get_response(url)
        all_info = get_info(response.text, all_info)
        time.sleep(random.random() * 4)

    imge_urls = map(lambda x: "{}com{}".format(temp_url[: temp_url.index("com")], x), all_info["next_url"])
    house_name = all_info['房源名称']
    get_img_and_download(imge_urls, house_name, path)
    save_data(path, all_info)


if __name__ == '__main__':
    temp_url = 'http://bj.lianjia.com/zufang/pg{}'
    path = './lianjia/image'
    # num = input('爬取的⻚数:')
    num = "2"
    if num.isdigit():
        num = int(num)
        print(main(num, path, temp_url))
    else:
        print('num输⼊的不是纯数字')
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值