一.什么是爬虫

网络爬虫(又称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。

爬虫能做什么

网络爬虫通俗的讲就是通过程序去获取web页面上自己想要的数据,也就是自动抓取数据。

二.用Python爬虫爬取链家网页(并存入数据库)

1.引入我们所需要的第三方库

​import random
import re  # 正则表达式
import time
import pandas as pd   # 文件处理
import requests  # 请求数据
from numpy import *  # 创建给定类型的矩阵,并初始化为0
import matplotlib.pyplot as plt  # 数据可视化
import pymysql  # 链接数据库
import matplotlib as mpl  # 绘图库​

2.通过循环爬取N页租房信息

def get_data():'''通过循环获取租房信息:return:'''for i in range(1, 2):print('正在爬取第%d页' % (i))# 爬取成都链家网租房信息baseurl = 'https://cd.lianjia.com/zufang/pg'url = baseurl + str(i) + '/#contentList'header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}print(url)response = requests.get(url, headers=header)html = response.textdata_list = []if response.status_code == 200:# 单独提取每个小区的信息regex = re.compile('title="(.*?)">\n.*?([0-9.]+)㎡\n.*?<em>([0-9.]+)</em> 元/月', re.DOTALL)data = regex.findall(html)  # 找出面积data = list(data)data_list.append(data)# print(data_house)# 每次随机休息1-5秒time.sleep(random.randint(1, 5))data_house = pd.DataFrame(data_list)return data_house, data_list

3.数据处理,提取出小区信息和租金

def process_data(data):res = []res_list = []for i in range(0, len(data)):res.append([data_list[0][i][0].split()[0][3:], data_list[0][i][2]])res_list.append([data_list[0][i][0].split()[0][:2],data_list[0][i][0].split()[0][3:],data_list[0][i][0].split()[1],data_list[0][i][0].split()[2],data_list[0][i][1],data_list[0][i][2]])return res, res_list

4.输入小区名称,输出该小区对应的平均租金

def query(x, y):name = '.*'.join(input('请输入小区名称:'))regex = re.compile(name)for i in range(0, len(x)):match = regex.search(x[i])if match:print(f'该小区{x[i]}的平均租金为:{y[i]}')

5.连接数据库,将爬取下来的信息存入数据库中

def store_data(data):# 连接数据库conn = pymysql.connect(user="root",port=3306,passwd="",db="spider",host="127.0.0.1",charset='utf8')if conn:print('数据库连接成功')error = 0try:cursor = conn.cursor()num = 0for item in data:print(item)num = num + 1x0 = str(item[0])x1 = str(item[1])x2 = str(item[2])x3 = str(item[3])x4 = str(item[4])x5 = str(item[5])insert_re = f'insert into rent(number, ways,town_name, layout,towards,area,rent) values ({num}, \'{x0}\',\'{x1}\',\'{x2}\',\'{x3}\',\'{x4}\',\'{x5}\')'print(insert_re)print(type(insert_re))cursor.execute(insert_re)conn.commit()except Exception as e:error = error + 1except UnicodeDecodeError as e:error = error + 1# 断开数据库连接conn.close()else:print('数据库连接失败')# 主函数
if __name__ == '__main__':data_house, data_list = get_data()print(data_list)res, res_list = process_data(data_list[0])# save_date(res_list)  # 信息保存到文件store_data(res_list)  # 数据存入数据库print(res)x, y= show(res)while True:query(x, y)

三.数据可视化

def show(data):res_1 = []x, y = [], []print(len(data))for i in range(0, len(data)):val = []for j in range(i, len(data)):if data_list[0][i][0].split()[0][3:] == data_list[0][j][0].split()[0][3:]:val.append(int(data_list[0][j][2]))res_1.append({data_list[0][i][0].split()[0][3:]: val})x.append(data_list[0][i][0].split()[0][3:])y.append(mean(val))print(x)print(len(x))print(y)print(len(y))# 解决中文显示问题mpl.rcParams['font.sans-serif'] = ['SimHei']mpl.rcParams['axes.unicode_minus'] = Falsefig, ax = plt.subplots(figsize=(8,4), dpi=100)ax.set_xlabel('小区名')ax.set_ylabel('平均租金')ax.set_title('该小区与平均租金之间的关系')bar = plt.bar(x, y, 0.5, color='coral', edgecolor='grey')plt.xticks(x, x, rotation=90)  # 这里是调度节横坐标的倾斜,rotation是度数# 显示数据标签for a, b in zip(x, y):plt.text(a, b,b,ha='center',va='bottom',)# 边框隐藏ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)plt.show()return x, ydef query(x, y):name = '.*'.join(input('请输入小区名称:'))regex = re.compile(name)for i in range(0, len(x)):match = regex.search(x[i])if match:print(f'该小区{x[i]}的平均租金为:{y[i]}')

Python爬虫爬取链家租房信息(python大作业)相关推荐

  1. python爬虫--爬取链家租房信息

    python 爬虫-链家租房信息 爬虫,其实就是爬取web页面上的信息. 链家租房信息页面如下: https://gz.lianjia.com/zufang/ ## python库 Python库 1 ...

  2. python爬虫代码房-python爬虫爬取链家二手房信息

    #coding=utf-8 import requests from fake_useragent import UserAgent from bs4 import BeautifulSoup imp ...

  3. Python爬虫爬取链家网上的房源信息练习

    一 原链接:用Python爬虫爬取链家网上的房源信息_shayebuhui_a的博客-CSDN博客_python爬取链家 打开链家网页:https://sh.lianjia.com/zufang/  ...

  4. python爬虫requests源码链家_python爬虫——爬取链家房价信息(未完待续)

    爬取链家房价信息(未完待续) items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # ...

  5. python爬虫爬取链家网房价信息

    打开链家网页:https://sh.lianjia.com/zufang/  :用F12以页面中元素进行检查 <a target="_blank" href="/z ...

  6. python爬虫爬取58同城租房信息(使用动态IP)输出Excel文件

    python爬虫爬取58同城信息(使用动态IP) 新手,为了做一个数据分析,搞了几天,终于搞出来了,大家可以给点意见啊. # coding=utf-8 import sys import csv im ...

  7. python爬虫requests源码链家_python爬虫爬取链家二手房信息

    #coding=utf-8 import requests from fake_useragent import UserAgent from bs4 import BeautifulSoup imp ...

  8. python二手房使用教程_python爬虫爬取链家二手房信息

    #coding=utf-8 import requests from fake_useragent import UserAgent from bs4 import BeautifulSoup imp ...

  9. 链家网开源java_异步协程爬取链家租房信息

    异步协程抓取链家数据+pandas写入csv import asyncio import aiohttp import pandas from bs4 import BeautifulSoup fro ...

  10. python爬取链家租房信息_Python爬取链家网上海市租房信息

    使用Python进行上海市租房信息爬取,通过requests + Beautifulsoup对网页内容进行抓取和数据提取. import requests from bs4 import Beauti ...

最新文章

  1. HDU 6015 Colorful Tree(2017多校)
  2. vc设置ani动画光标
  3. 深度学习Deep learning From Image to Sequence
  4. 老年市场是蓝海or沙漠?
  5. DropdownList 赋初始值问题
  6. 锲而不舍 —— M 是怎样找工作的?(八)
  7. [11] ADB 实用功能
  8. php 谈谈我对session, cookies和jwt的理解
  9. Fortran笔记,全局变量
  10. 没有IDEA与Eclipse,该怎么学Java?
  11. DevOps平台的“精益创业”之路
  12. 最新引流脚本之窃语漂流瓶引流脚本,如何使用窃语脚本
  13. 安利几本好看的书给你
  14. 微信小程序流量主广告怎么加圆角
  15. 汇编语言笔记(王爽)
  16. [新闻观察]中国网络“名人博客”风声水起
  17. latex中文小标题_LaTeX标题怎样使用中文?
  18. Mac 中不可错过的几款软件,相见恨晚!(基本免费)
  19. 一个有趣的英文文献翻译工具——CopyTranslator
  20. win10+NVIDIA geforce gtx 960M+cuda9.0+cudnn7.1+pytorch_1.1.0+torchvision_0.3.0---已解决

热门文章

  1. 服务器word文档会是只读的,Word自动变只读模式怎么办? 这样可取消Word只读
  2. 高颜值挂脖式运动蓝牙耳机盘点,五款3D环绕高音质蓝牙耳机测评分享
  3. bzoj 2827 千山鸟飞绝 平衡树
  4. 交通分析小区TAZ生成——以武汉市为例
  5. C++ 如何改变鼠标光标位置
  6. 西安交通大学电子图书站点被黑
  7. 关于2440嵌入式MPlayer播放器的移植方法
  8. 数据结构小知识点——广义表 “朝闻道”知识分享大赛
  9. 支付宝支付后页面跳转
  10. 编曲宿主DAW是什么 2023年编曲宿主软件哪个好用