Python爬虫项目--爬取链家热门城市新房
本次实战是利用爬虫爬取链家的新房(声明: 内容仅用于学习交流, 请勿用作商业用途)
环境
win8, python 3.7, pycharm
正文
1. 目标网站分析
通过分析, 找出相关url, 确定请求方式, 是否存在js加密等.
2. 新建scrapy项目
1. 在cmd命令行窗口中输入以下命令, 创建lianjia项目
scrapy startproject lianjia
2. 在cmd中进入lianjia文件中, 创建Spider文件
cd lianjia
scrapy genspider -t crawl xinfang lianjia.com
这次创建的是CrawlSpider类, 该类适用于批量爬取网页
3. 新建main.py文件, 用于执行scrapy项目文件
到现在, 项目就创建完成了, 下面开始编写项目
3 定义字段
在items.py文件中定义需要的爬取的字段信息
import scrapy
from scrapy.item import Item, Field class LianjiaItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
city = Field() #城市名
name = Field() #楼盘名
type = Field() #物业类型
status = Field() #状态
region = Field() #所属区域
street = Field() #街道
address = Field() #具体地址
area = Field() #面积
average_price = Field() #平均价格
total_price = Field() #总价
tags = Field() #标签
4 爬虫主程序
在xinfang.py文件中编写我们的爬虫主程序
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from lianjia.items import LianjiaItem class XinfangSpider(CrawlSpider):
name = 'xinfang'
allowed_domains = ['lianjia.com']
start_urls = ['https://bj.fang.lianjia.com/']
#定义爬取的规则, LinkExtractor是用来提取链接(其中,allow指允许的链接格式, restrict_xpaths指链接处于网页结构中的位置), follow为True表示跟进提取出的链接, callback则是调用函数
rules = (
Rule(LinkExtractor(allow=r'\.fang.*com/$', restrict_xpaths='//div[@class="footer"]//div[@class="link-list"]/div[2]/dd'), follow=True),
Rule(LinkExtractor(allow=r'.*loupan/$', restrict_xpaths='//div[@class="xinfang-all"]/div/a'),callback= 'parse_item', follow=True)
)
def parse_item(self, response):
'''请求每页的url''''
counts = response.xpath('//div[@class="page-box"]/@data-total-count').extract_first()
pages = int(counts) // 10 + 2
#由于页数最多为100, 加条件判断
if pages > 100:
pages = 101
for page in range(1, pages):
url = response.url + "pg" + str(page)
yield scrapy.Request(url, callback=self.parse_detail, dont_filter=False) def parse_detail(self, response):
'''解析网页内容'''
item = LianjiaItem()
item["title"] = response.xpath('//div[@class="resblock-have-find"]/span[3]/text()').extract_first()[1:]
infos = response.xpath('//ul[@class="resblock-list-wrapper"]/li')
for info in infos:
item["city"] = info.xpath('div/div[1]/a/text()').extract_first()
item["type"] = info.xpath('div/div[1]/span[1]/text()').extract_first()
item["status"] = info.xpath('div/div[1]/span[2]/text()').extract_first()
item["region"] = info.xpath('div/div[2]/span[1]/text()').extract_first()
item["street"] = info.xpath('div/div[2]/span[2]/text()').extract_first()
item["address"] = info.xpath('div/div[2]/a/text()').extract_first().replace(",", "")
item["area"] = info.xpath('div/div[@class="resblock-area"]/span/text()').extract_first()
item["average_price"] = "".join(info.xpath('div//div[@class="main-price"]//text()').extract()).replace(" ", "")
item["total_price"] = info.xpath('div//div[@class="second"]/text()').extract_first()
item["tags"] = ";".join(info.xpath('div//div[@class="resblock-tag"]//text()').extract()).replace(" ","").replace("\n", "")
yield item
5 保存到Mysql数据库
在pipelines.py文件中编辑如下代码
import pymysql
class LianjiaPipeline(object):
def __init__(self):
#创建数据库连接对象
self.db = pymysql.connect(
host = "localhost",
user = "root",
password = "",
port = 3306,
db = "lianjia",
charset = "utf8"
)
self.cursor = self.db.cursor()
def process_item(self, item, spider):
#存储到数据库中
sql = "INSERT INTO xinfang(city, name, type, status, region, street, address, area, average_price, total_price, tags) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
data = (item["city"], item["name"], item["type"], item["status"], item["region"], item["street"], item["address"], item["area"], item["average_price"], item["total_price"], item["tags"])
try:
self.cursor.execute(sql, data)
self.db.commit()
except:
self.db.rollback()
finally:
return item
6 反反爬措施
由于是批量性爬取, 有必要采取些反反爬措施, 我这里采用的是免费的IP代理. 在middlewares.py中编辑如下代码:
from scrapy import signals
import logging
import requests
class ProxyMiddleware(object):
def __init__(self, proxy):
self.logger = logging.getLogger(__name__)
self.proxy = proxy
@classmethod
def from_crawler(cls, crawler):
'''获取随机代理的api接口'''
settings = crawler.settings
return cls(
proxy=settings.get('RANDOM_PROXY')
)
def get_random_proxy(self):
'''获取随机代理'''
try:
response = requests.get(self.proxy)
if response.status_code == 200:
proxy = response.text
return proxy
except:
return False
def process_request(self, request, spider):
'''使用随机生成的代理请求'''
proxy = self.get_random_proxy()
if proxy:
url = 'http://' + str(proxy)
self.logger.debug('本次使用代理'+ proxy)
request.meta['proxy'] = url
7 配置settings文件
import random
RANDOM_PROXY = "http://localhost:6686/random"
BOT_NAME = 'lianjia'
SPIDER_MODULES = ['lianjia.spiders']
NEWSPIDER_MODULE = 'lianjia.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = random.random()*2
COOKIES_ENABLED = False
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
DOWNLOADER_MIDDLEWARES = {
'lianjia.middlewares.ProxyMiddleware': 543
}
ITEM_PIPELINES = {
'lianjia.pipelines.LianjiaPipeline': 300,
}
8 执行项目文件
在mian.py中执行如下命令
from scrapy import cmdline
cmdline.execute('scrapy crawl xinfang'.split())
scrapy项目即可开始执行, 最后爬取到1万4千多条数据.
Python爬虫项目--爬取链家热门城市新房的更多相关文章
- python爬虫:爬取链家深圳全部二手房的详细信息
1.问题描述: 爬取链家深圳全部二手房的详细信息,并将爬取的数据存储到CSV文件中 2.思路分析: (1)目标网址:https://sz.lianjia.com/ershoufang/ (2)代码结构 ...
- python爬虫项目-爬取雪球网金融数据(关注、持续更新)
(一)python金融数据爬虫项目 爬取目标:雪球网(起始url:https://xueqiu.com/hq#exchange=CN&firstName=1&secondName=1_ ...
- Python爬虫项目--爬取自如网房源信息
本次爬取自如网房源信息所用到的知识点: 1. requests get请求 2. lxml解析html 3. Xpath 4. MongoDB存储 正文 1.分析目标站点 1. url: http:/ ...
- Python爬虫项目--爬取猫眼电影Top100榜
本次抓取猫眼电影Top100榜所用到的知识点: 1. python requests库 2. 正则表达式 3. csv模块 4. 多进程 正文 目标站点分析 通过对目标站点的分析, 来确定网页结构, ...
- Python爬虫项目--爬取某宝男装信息
本次爬取用到的知识点有: 1. selenium 2. pymysql 3 pyquery 正文 1. 分析目标网站 1. 打开某宝首页, 输入"男装"后点击"搜索&q ...
- python爬虫:利用BeautifulSoup爬取链家深圳二手房首页的详细信息
1.问题描述: 爬取链家深圳二手房的详细信息,并将爬取的数据存储到Excel表 2.思路分析: 发送请求--获取数据--解析数据--存储数据 1.目标网址:https://sz.lianjia.com ...
- Python的scrapy之爬取链家网房价信息并保存到本地
因为有在北京租房的打算,于是上网浏览了一下链家网站的房价,想将他们爬取下来,并保存到本地. 先看链家网的源码..房价信息 都保存在 ul 下的li 里面 爬虫结构: 其中封装了一个数据库处理模 ...
- 【nodejs 爬虫】使用 puppeteer 爬取链家房价信息
使用 puppeteer 爬取链家房价信息 目录 使用 puppeteer 爬取链家房价信息 页面结构 爬虫库 pupeteer 库 实现 打开待爬页面 遍历区级页面 方法一 方法二 遍历街道页面 遍 ...
- Python——Scrapy爬取链家网站所有房源信息
用scrapy爬取链家全国以上房源分类的信息: 路径: items.py # -*- coding: utf-8 -*- # Define here the models for your scrap ...
随机推荐
- zombodb 聚合函数
zombodb 暴露基本上所有es 的集合函数为sql 函数,我们可以方便使用 比如 count FUNCTION zdb.count( index regclass, query zdbquery) ...
- CRM项目之stark组件
. stark也是一个app(用startapp stark创建),目标时把这个做成一个可以拔插的组件 . setting文件下INSTALLED_APPS 路径要配置好(app的注册) . 写好si ...
- grafna与饼状图
官网: https://grafana.com/plugins/grafana-piechart-panel/installation https://grafana.com/p ...
- Hanlp自然语言处理中的词典格式说明
使用过hanlp的都知道hanlp中有许多词典,它们的格式都是非常相似的,形式都是文本文档,随时可以修改.本篇文章详细介绍了hanlp中的词典格式,以满足用户自定义的需要. 基本格式 词典分为词频词性 ...
- Spark Streaming 'numRecords must not be negative'问题解决
转载自:http://blog.csdn.net/xueba207/article/details/51135423 问题描述 笔者使用spark streaming读取Kakfa中的数据,做进一步处 ...
- AIUI开放平台:多轮对话返回前几轮语槽数据
编写云函数: AIUI.create("v2", function(aiui, err){ // 获取 response response = aiui.getResponse() ...
- UEFI和GPT下硬盘克隆后的BCD引导修复
UEFI和GPT下硬盘克隆后的BCD引导修复-Storm_Center http://www.stormcn.cn/post/1901.html 当硬盘引导换成GPT,系统启动也变成UEFI后,如果直 ...
- mysql识别中文
在配置的INI中加上这些 [mysql]default-character-set=utf8no-auto-rehash# Remove the next comment character if y ...
- C/C++中的volatile简单描述
首先引入一篇博客: 1. 为什么用volatile? C/C++ 中的 volatile 关键字和 const 对应,用来修饰变量,通常用于建立语言级别的 memory barrier.这是 BS 在 ...
- [UE4]Image
一.Image.Appearance.Brush.Tiling:平铺方式 1.No Tile:不平铺,拉伸会变形 2.Horizontal:横向平铺.纵向拉伸会变形 3.Vertical:纵向平铺.横 ...