思路和上一篇差不多,先获取网站html文件,使用BeautifulSoup进行解析,将对应属性取出,逐一处理,最后把整理出的记录保存到oracle中,持久化储存。

'''
Created on 2017年2月20日

@author: Administrator
'''
from urllib import parse, request
from bs4 import BeautifulSoup
from sqlalchemy import create_engine
from datetime import *

import numpy as np
import pandas as pd
import time
import re
import socket
import traceback
import logging

def get_page(url):
    headers = {
        'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
        'Referer': r'http://jinan.anjuke.com/sale/b151-m161-o5-p1/',
        'Host': r'jinan.anjuke.com',
        'Connection': 'keep-alive'
    }
    timeout = 60
    socket.setdefaulttimeout(timeout)  # 设置超时
    req = request.Request(url, headers=headers)
    response = request.urlopen(req).read()
    page = response.decode('utf-8','ignore')
    return page
if __name__ == '__main__':  
   
    curDate = date.strftime(date.today(),'%Y%m%d',)
    logName =  'Anjuke_%s.log' %curDate
    logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename=logName,
                filemode='a')
   
    url = 'http://jinan.anjuke.com/sale/b151-m161-o5-p1/?from_price=150&to_price=250&from_area=120&to_area=200'
    html = get_page(url)
    soup =  BeautifulSoup(html,"lxml")
    table =soup.find_all('li','list-item')
   
    df = pd.DataFrame(columns=["address","floor","house_name","href","m2","price","room","unit_price","web","year","op_time"])
   
    for tr in table:
        #名称
        str_name = tr.find("div","house-title").find('a').string.strip()
        ##连接
        str_href = tr.find("a","houseListTitle")["href"]
       
        ##房产属性
        str_ts = list()
        for s in tr.find("div","details-item").find_all('span'):           
            str_ts.append(s.string)
        room = str_ts[0]
        m2 =re.findall(r"(\d+\.*\d+)",str_ts[1])
        floor = str_ts[2]
        year = str_ts[3]
       
        ##地址信息
        str_add = tr.find("span","comm-address").string.strip()
        str_add = re.sub(r"(\xa0\xa0\n)","",str_add)
        ##价格
        str_price = tr.find("div","pro-price").find('span','price-det')
        str_price = re.findall(r"(\d+\.*\d+)",str_price.text)
        str_unit_price = re.findall(r"(\d+\.*\d+)",tr.find("div","pro-price").find('span','unit-price').text)
       
        row = {'web':'安居客','house_name':str_name,'room':room,'m2':m2,'price':str_price,'unit_price':str_unit_price,'floor':floor,'year':year,'address':str_add,'href':str_href}
        #print(row)
        newrow = pd.DataFrame(data=row,index=["0"])
        df=df.append(newrow,ignore_index=True)
    #df.reset_index(drop = True)
    df["op_time"]=time.strftime('%Y-%m-%d',time.localtime(time.time()))
    df['m2'] = df['m2'].astype('int')
    df['price'] = df['price'].astype('int')
    df['unit_price'] = df['unit_price'].astype('int')
   
    ##建立数据库连接
    engine = create_engine('oracle+cx_oracle://user:pass@localhost/orcl')
    cnx = engine.connect() 
    try:
        df.to_sql('anju_house', cnx,if_exists='append',index=False)
    except Exception as e:
        logging.error(traceback.format_exc())
    ##关闭数据链接
    cnx.close()

简单抓取安居客房产数据,并保存到Oracle数据库的更多相关文章

  1. node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中

    步骤一:安装必要模块 (1)cheerio模块 ,一个类似jQuery的选择器模块,分析HTML利器. (2)request模块,让http请求变的更加简单 (3)mysql模块,node连接mysq ...

  2. java网络爬虫----------简单抓取慕课网首页数据

    © 版权声明:本文为博主原创文章,转载请注明出处 一.分析 1.目标:抓取慕课网首页推荐课程的名称和描述信息 2.分析:浏览器F12分析得到,推荐课程的名称都放在class="course- ...

  3. 使用pandas中的raad_html函数爬取TOP500超级计算机表格数据并保存到csv文件和mysql数据库中

    参考链接:https://www.makcyun.top/web_scraping_withpython2.html #!/usr/bin/env python # -*- coding: utf-8 ...

  4. 快速将excel数据保存到Oracle数据库中【转】

    我们在工作中,也许会碰到以下情况,客户或者同事发来需要调查的数据,并不是dmp文件,而是excel文件,此时通常是一张表,少量几条记录.最近我恰好碰到了这种情况,所以做了些调查,不敢藏私,拿出来跟大家 ...

  5. 使用 Python 抓取欧洲足球联赛数据

    Web Scraping在大数据时代,一切都要用数据来说话,大数据处理的过程一般需要经过以下的几个步骤    数据的采集和获取    数据的清洗,抽取,变形和装载    数据的分析,探索和预测    ...

  6. 抓取Js动态生成数据且以滚动页面方式分页的网页

    代码也可以从我的开源项目HtmlExtractor中获取. 当我们在进行数据抓取的时候,如果目标网站是以Js的方式动态生成数据且以滚动页面的方式进行分页,那么我们该如何抓取呢? 如类似今日头条这样的网 ...

  7. 如何用python抓取js生成的数据 - SegmentFault

    如何用python抓取js生成的数据 - SegmentFault 如何用python抓取js生成的数据 1赞 踩 收藏 想写一个爬虫,但是需要抓去的的数据是js生成的,在源代码里看不到,要怎么才能抓 ...

  8. Python爬虫抓取东方财富网股票数据并实现MySQL数据库存储

    Python爬虫可以说是好玩又好用了.现想利用Python爬取网页股票数据保存到本地csv数据文件中,同时想把股票数据保存到MySQL数据库中.需求有了,剩下的就是实现了. 在开始之前,保证已经安装好 ...

  9. php使用curl简单抓取远程url的方法

    这篇文章主要介绍了php使用curl简单抓取远程url的方法,涉及php操作curl的技巧,具有一定参考借鉴价值,需要的朋友可以参考下     本文实例讲述了php使用curl抓取远程url的方法.分 ...

随机推荐

  1. poj1379 Run Away

    传送门:http://poj.org/problem?id=1379 [题解] 题目大意:求(0,0)->(X,Y)内的一个点,使得这个点到给定的n个点的最小距离最大. 模拟退火 一开始可以先把 ...

  2. USACO月赛2005 january volume

    2013-09-18 08:12 由题可知,ans=∑i  ∑j(x[i]-x[j]) 最后整理完之后应该是不同系数的X[i]相加,所以这道题就成了求不同x[i]的系数 对于X[i],它需要减前面(i ...

  3. bzoj 2753 最小生成树变形

    我们根据高度建图,将无向边转化为有向边 首先对于第一问,直接一个bfs搞定,得到ans1 然后第二问,我们就相当于要求找到一颗最小生成树, 满足相对来说深度小的高度大,也就是要以高度为优先级 假设现在 ...

  4. html 表格获取单行

    参考:http://www.jb51.net/article/63161.htm function cell(btn_id) { {#var x=document.getElementById('#' ...

  5. exec,eval

    一.什么是Exec语句 假如我们一串字符串里面有Python代码,这个时候,普通情况是会把这串代码作为字符串来输出的,而不会执行这段代码.如果此时,我们想执行这串字符串里面的python代码,使用Ex ...

  6. Kuangbin 带你飞-基础计算几何专题 题解

    专题基本全都是模版应用.贴一下模版 平面最近点对 const double INF = 1e16; ; struct Point { int x,y; int type; }; double dist ...

  7. linux shell 脚本实现tcp/upd协议通讯(重定向应用)

    linux shell 脚本实现tcp/upd协议通讯(重定向应用) http://www.cnblogs.com/chengmo/archive/2010/10/22/1858302.html

  8. jquery 操作dom效率测试------html和append插入文档

    $(function () { var htmlResult = createHtmlContent(100); console.log(htmlResult) insertHtml.call($(& ...

  9. Nessus home与Nexpose community 对比

    转载请注明来源:http://www.cnblogs.com/phoenix--/p/3345569.html 更新:Nessus home版限制了,总量:16,Nexpose限制了总量为32,全部没 ...

  10. Oralce聚合多行

    拼接的字符串长度满足varchar2(4000)时, 可以用 LISTAGG(NAME, '_') WITHIN GROUP(ORDER BY LEVEL_T DESC) 当拼接大段文本时,采用 10 ...