Python爬虫实战之爬取链家广州房价_01简单的单页爬虫

本文介绍了一种使用Python2.7爬取链家广州所有小区信息的方法,包括在售楼盘及历史成交记录。通过模拟浏览器行为设置headers,并解决字符编码问题,采用BeautifulSoup进行网页解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路介绍

爬取链家广州所有小区信息、在售楼盘及所有历史成交记录,对于超过100个页面的信息,采用曲线爬取的方式,先爬每个小区,然后爬每个小区的在售楼盘及成交记录,后期将进行相应更新,进一步研究Cookie的使用、Proxy(代理)的设置、模拟登录、验证码识别等问题。环境基于Python 2.7。

请求

这里我使用的package是urllib和urllib2,这里列一下爬取过程中需要注意的一些问题。
- 模拟浏览器的行为,设置headers。
- Python 2.x中常见的字符编码和解码问题

首先了解一下字节、字符和编码的关系,ASCII、Unicode和UTF-8的关系,ASCII码一共规定了128个字符的编码,Unicode是一个符号集,只规定了符号的二进制代码,没有规定此二进制代码应该如何存储,结果出现Unicode的多种存储方式,即有许多种不同的二进制格式,可以用来表示Unicode。而UTF-8就是目前使用最广的一种Unicode的实现方式。

Python 2.x里有两种类型的字符串类型:字节字符串和Unicode的字符串。Python根据电脑默认的locale设置将字节转换为字符。

# 获取系统默认的编码方式
<<< import sys
<<< print sys.getdefaultencoding()
'ascii'  # windows默认的编码是ascii
# 更改系统的默认编码
<<< import sys
<<< reload(sys)
<<< sys.setdefaultencoding('UTF-8')
# 为什么reload(sys)
# Python运行时首先加载site.py,把setdefaultencoding方法删除了
if hasattr(sys, "setdefaultencoding"):
    del sys.setdefaultencoding
# Python源代码默认是ASCII,可以在源文件开头作如下声明
# -*- coding: UTF-8 -*-
# 读取UTF-8编码的文件,可以手工转换从文件中读取的字符串
<<< import codecs
<<< fileObj = codecs.open("someFile", "r", "UTF-8")
# Returns a Unicode string from the UTF-8 bytes in the file
<<< u = fileObj.read()

Python的decode函数和encode函数,decode是将普通字符串按照参数指定编码格式进行解析,然后生成相应的Unicode对象,encode函数是将一个Unicode对象转换为参数中编码格式的普通字符。

<<< s1 = '哈'.decode('utf-8')
u'\u54c8'
<<< s2 = '哈'.decode('utf-8').encode('utf-8')
'\xe5\x93\x88'

解析

这里采用的是BeautifulSoup,采用标准库中的html解析器,配合正则表达式进行解析。

单页爬虫的代码示例

#! python2
# -*- coding: utf-8 -*-
"""crawl module

@Author: padluo
@WeChat: padluo
"""
import random
import re
import urllib2

from bs4 import BeautifulSoup

HDS = [
    {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},
    {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'},
    {
        'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'},
    {
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0'},
    {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/44.0.2403.89 Chrome/44.0.2403.89 Safari/537.36'},
    {
        'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'},
    {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'},
    {
        'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'},
    {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'},
    {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'},
    {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'},
    {
        'User-Agent': 'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11'},
    {
        'User-Agent': 'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11'}
]


def xiaoqu_crawl(db_xq=None,
                 url_page=u'http://gz.lianjia.com/xiaoqu/pg1rs%E9%87%91%E7%A2%A7%E4%B8%96%E7%BA%AA%E8%8A%B1%E5%9B%AD/'):
    """爬取页面链接中的小区信息

    :param db_xq:
    :param url_page:
    :return:
    """
    try:
        # 请求
        url_page = u'http://gz.lianjia.com/xiaoqu/pg1rs%E9%87%91%E7%A2%A7%E4%B8%96%E7%BA%AA%E8%8A%B1%E5%9B%AD/'
        req = urllib2.Request(url_page,
                              headers=HDS[random.randint(0, len(HDS) - 1)])
        source_code = urllib2.urlopen(req, timeout=10).read()
        plain_text = source_code.decode('utf-8')
        soup = BeautifulSoup(plain_text, 'html.parser')
    except (urllib2.HTTPError, urllib2.URLError), e:
        print e
        exit(-1)
    except Exception, e:
        print e
        exit(-1)
    # 解析
    xiaoqu_list = soup.find_all('div', attrs={'class': 'info'})
    for xq in xiaoqu_list:
        info_dict = {}
        info_dict.update({u'小区链接': xq.find('a')['href']})
        info_dict.update(
            {u'小区名称': xq.find('a', attrs={'target': '_blank'}).get_text()})
        content = xq.find('div', attrs={
            'class': 'houseInfo'}).renderContents().strip().decode('utf-8')
        pat = r'<span.*?/span>.*?<a.*?>(.*?)</a>.*?<a.*?>(.*?)</a>'
        info = re.match(pat, content, re.S)
        if info:
            info = info.groups()
            info_dict.update({u'90天成交量': info[0]})
            info_dict.update({u'正在出租量': info[1]})
        content = xq.find('div', attrs={
            'class': 'positionInfo'}).renderContents().strip().decode('utf-8')
        pat = r'<span.*?span>.*?<a.*?>(.*?)</a>.*?<a.*?>(.*?)</a>.*?/\xa0(.*)'
        info = re.match(pat, content, re.S)
        if info:
            info = info.groups()
            info_dict.update({u'大区域': info[0]})
            info_dict.update({u'小区域': info[1]})
            info_dict.update({u'建成时间': info[2]})
        for info_key, info_value in info_dict.items():
            print info_key + '->' + info_value


if __name__ == '__main__':
    xiaoqu_crawl()

结果如下:

小区链接->http://gz.lianjia.com/xiaoqu/2111103317968/
大区域->黄埔
建成时间->2004年建成
正在出租量->20套正在出租
小区域->区府
小区名称->金碧世纪花园
90天成交量->90天成交11
好的,这是一个很不错的爬虫入门练习。首先,你需要安装 Python 的 requests 和 BeautifulSoup 库。安装方法可以在官方文档中找到。 接下来,你需要分析网二手房信息的页面结构,找到需要爬取数据。可以使用 Chrome 开发者工具来查看网页源代码和网络请求。通常情况下,你需要模拟浏览器发送请求,获取网页内容,然后使用 BeautifulSoup 解析 HTML,提取数据。 以下是一个简单的示例代码,用于爬取网二手房信息: ```python import requests from bs4 import BeautifulSoup url = 'https://bj.lianjia.com/ershoufang/' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') house_list = soup.find_all('div', class_='info') for house in house_list: title = house.find('div', class_='title').a.text.strip() address = house.find('div', class_='address').div.text.strip() price = house.find('div', class_='price').span.text.strip() print(title, address, price) ``` 在这个示例中,我们首先发送一个 GET 请求到网二手房信息的页面。然后使用 BeautifulSoup 解析 HTML,获取每个房源的标题、地址和价格信息。最后打印这些信息。 当然,这只是一个简单的示例代码,你可以根据自己的需要进行修改和调整。同时,需要注意的是,爬取网站数据是需要遵守相关法律法规和网站的使用协议的。在爬取数据之前,请先了解相关规定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值