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 ...
随机推荐
- jar包不能乱放【浪费了下午很多时间】
不能放在类路径下(也即是src文件夹下),然后再buildpath 必须放在web-inf文件夹下 这样才能tomcat找打jar文件
- 十九、springcloud(五)配置中心本地示例和refresh
1.创建spring-cloud-houge-config子项目,测试需要的项目入下 2.添加依赖 <dependency> <groupId>org.springframew ...
- Excel技巧--分隔工资条
要将上图的工资表,做成每行都带标题而且有空行间隔的工资条,可以这么做: 1.表格右侧添加一列数据列:输入1,2,选定,并双击单元格右下角形成一升序数字列: 2.再将该列复制,粘贴到该列末尾: 3.点一 ...
- 【Python】断言功能Assertion
转自 https://www.cnblogs.com/cicaday/p/python-assert.html Python Assert 为何不尽如人意 Python中的断言用起来非常简单,你可以在 ...
- 兼容ie,火狐的判断回车键js脚本
var event = window.event || arguments.callee.caller.arguments[0]; var keycode = event.keyCode || eve ...
- Linux vim快捷键
1 替换 r 替换 先按r再按要替换的内容 2 按yy复制当前行 按p是粘贴 3 # add at 18-10-25 #-------------------------------- ...
- C++Primer第五版——习题答案详解(七)
习题答案目录:https://www.cnblogs.com/Mered1th/p/10485695.html 第8章 IO库 练习8.1 istream &iofunc(istream &a ...
- vue+element 实现在表格内插入其他组件,每行数据独立存储
使用 v-slot row代表当前行
- 浅析MySQL中concat以及group_concat的使用
说明: 本文中使用的例子均在下面的数据库表tt2下执行: 一.concat()函数 1.功能:将多个字符串连接成一个字符串. 2.语法:concat(str1, str2,...) 返回结果为连接 ...
- 【HQL】小技巧
case1.a与b匹配表保留一条匹配关系 背景:匹配b,b匹配a在同一张表: match_table表为: uid,m_uid 111,222 222,111 需求:只保留一条匹配关系. 结果为: u ...