使用python爬取链家上海二手房信息的案例

孤者浪人 提交于 2019-12-08 21:16:44

使用python爬取链家上海二手房信息的案例

1、需求分析

爬取链家网上海的二手房信息,包括名称、户型、面积、价格信息,并将爬取到的信息写入到数据库中。

2、步骤分析

2.1 确定待爬取的url

https://sh.lianjia.com/ershoufang/pg

在谷歌浏览器中查看网页源代码:ctrl+shif+i,先点击图中左上角框中的按钮,再在网页中点击需要查看的内容就会定位到对应的代码。
图1

2.2确定爬取的数据

确定爬取的名称和户型的标签为 data-el=”region”
图2
确定爬取的二手房的价格的标签class类名:class=”totalPrice”
图3

3、代码实现

#从urllib中导入request,接受一个Request类的实例来设置URL请求的headers
from urllib import request
#导入正则表达式模块
import re
#导入pymysql,将爬取到的数据写入mysql中
import pymysql

def HTMLspider(url,startPage,endPage):

    #作用:负责处理URL,分配每个URL去发送请求

    for page in range(startPage,endPage+1):
        filename="第" + str(page) + "页.html"
        #组合为完整的url
        fullurl=url + str(page) +"/"

        #调用loadPage()发送请求,获取HTML页面
        html=loadPage(fullurl,filename)

def loadPage(fullurl,filename):
     #下载页面 
    response=request.urlopen(fullurl)
    Html=response.read().decode('utf-8')
    #print(Html)
    #正则编译,获取名称和户型
    info_pattern=r'data-el="region">(.+?)</div>'
    info_list=re.findall(info_pattern,Html)
    #print(info_list)
    #正则编译,获取二手房价格
    price_pattern=r'<div class="totalPrice"><span>\d+</span>万'
    price_list=re.findall(price_pattern,Html)
    #print(price_list)

    dealPage(price_list,info_list,filename)


def dealPage(price_list,info_list,filename):
    """
    将服务器的响应文件保存到本地磁盘
    """
    list1=[]
    list2=[]
    list3=[]
    #名称,户型,价格都是一一对应的列表格式,用for循环遍历
    for i in price_list:
        i= i[30:-8] + '万'
        list1.append(i)
    for j in info_list:
        j=j.replace('</a>',' '*10)
        local=j[:10]
        info=j[10:] 
        list2.append(local)
        list3.append(info)
        for k in range(len(list1)):
        print(list2[k] + list3[k] + list1[k])

    print("正在存储"+filename)
    #输出横线隔开
    print("--"*30)
    connsql(list1,list2,list3)
#创建一个数据库操作对象
def connsql(list1,list2,list3):
    #使用pymysql获取mysql数据连接
    conn = pymysql.connect(host='127.0.0.1', user='root', password='950822r', db='houseinfo',charset="utf8")
    #获取数据操作对象
    cur = conn.cursor()

    for i in range(len(list1)):
        a=str(list2[i])
        b=str(list3[i])
        c=str(list1[i])
        #操作mysql语句
        sqla=("INSERT INTO  coffee(name,info,price)" " VALUES (%s,%s,%s)")
        #将一一对应的列表写入data字典中
        data=(a,b,c)
        #执行SQL语句
        B = cur.execute(sqla,data)
        #事物提交
        conn.commit()
        #关闭连接对象执行对象
    cur.close()
    conn.close()
#如果直接使用本文件就执行
if __name__=="__main__":
    #输入需要下载的起始页和终止页,注意转换成int类型
    startPage=int(input("请输入起始页:"))
    endPage=int(input("请输入终止页:"))
    #链接到爬虫的网页
    url="https://sh.lianjia.com/ershoufang/pg"
    #调用网页爬虫函数,传递值url,起始页和终止页
    HTMLspider(url,startPage,endPage)
    print("下载完成!")

4、执行结果

(1)控制台执行结果片段
这里写图片描述
(2)爬取的数据写到数据库的结果
这里写图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!