python爬取链家新房_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文件中定义需要的爬取的字段信息
importscrapyfrom scrapy.item importItem, FieldclassLianjiaItem(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 importLinkExtractorfrom scrapy.spiders importCrawlSpider, Rulefrom lianjia.items importLianjiaItemclassXinfangSpider(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)
)defparse_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)defparse_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 ininfos:
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文件中编辑如下代码
importpymysqlclassLianjiaPipeline(object):def __init__(self):#创建数据库连接对象
self.db =pymysql.connect(
host= "localhost",
user= "root",
password= "1234",
port= 3306,
db= "lianjia",
charset= "utf8")
self.cursor=self.db.cursor()defprocess_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 importsignalsimportloggingimportrequestsclassProxyMiddleware(object):def __init__(self, proxy):
self.logger= logging.getLogger(__name__)
self.proxy=proxy
@classmethoddeffrom_crawler(cls, crawler):'''获取随机代理的api接口'''settings=crawler.settingsreturncls(
proxy=settings.get('RANDOM_PROXY')
)defget_random_proxy(self):'''获取随机代理'''
try:
response=requests.get(self.proxy)if response.status_code == 200:
proxy=response.textreturnproxyexcept:returnFalsedefprocess_request(self, request, spider):'''使用随机生成的代理请求'''proxy=self.get_random_proxy()ifproxy:
url= 'http://' +str(proxy)
self.logger.debug('本次使用代理'+proxy)
request.meta['proxy'] = url
7 配置settings文件
importrandom
RANDOM_PROXY= "http://localhost:6686/random"BOT_NAME= 'lianjia'SPIDER_MODULES= ['lianjia.spiders']
NEWSPIDER_MODULE= 'lianjia.spiders'ROBOTSTXT_OBEY=False
DOWNLOAD_DELAY= random.random()*2COOKIES_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 importcmdline
cmdline.execute('scrapy crawl xinfang'.split())
scrapy项目即可开始执行, 最后爬取到1万4千多条数据.
python爬取链家新房_Python爬虫项目--爬取链家热门城市新房相关推荐
- python爬虫金融数据_python爬虫项目-爬取雪球网金融数据(关注、持续更新)
(一)python金融数据爬虫项目 爬取目标:雪球网(起始url:https://xueqiu.com/hq#exchange=cn&firstname=1&secondname=1_ ...
- python爬取多页数据_python爬虫实现爬取同一个网站的多页数据代码实例
本篇文章小编给大家分享一下python爬虫实现爬取同一个网站的多页数据代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. 一.爬虫的目的 从网上获 ...
- python爬虫爬取58网站数据_Python爬虫,爬取58租房数据 字体反爬
Python爬虫,爬取58租房数据 这俩天项目主管给了个爬虫任务,要爬取58同城上福州区域的租房房源信息.因为58的前端页面做了base64字体加密所以爬取比较费力,前前后后花了俩天才搞完. 项目演示 ...
- python爬取网店数据_Python爬虫实现抓取京东店铺信息及下载图片功能示例
本文实例讲述了Python爬虫实现抓取京东店铺信息及下载图片功能.分享给大家供大家参考,具体如下: 这个是抓取信息的 from bs4 import BeautifulSoup import requ ...
- python爬取豆瓣电影信息_Python爬虫入门 | 爬取豆瓣电影信息
这是一个适用于小白的Python爬虫免费教学课程,只有7节,让零基础的你初步了解爬虫,跟着课程内容能自己爬取资源.看着文章,打开电脑动手实践,平均45分钟就能学完一节,如果你愿意,今天内你就可以迈入爬 ...
- python爬取京东手机参数_python爬虫——分页爬取京东商城商品信息(手机为例)...
1.最近刚开始学习python 写了个爬虫练习,感觉主要是得会用F12查询网站结构代码.还涉及到反爬虫,每个网站都不一样,拿到的解析出的json数据格式也不同.得有些Web知识的基础才行. htt ...
- python爬取历史天气查询_Python爬虫实战-爬取历史天气数据
最近项目需要对合肥市历史天气数据进行爬取,分析了几个天气数据网站,最终选择天气后报网站. 将实现过程遇到的问题以及下来,供以后参考. 步骤分析 这里我使用的是Python中的requests库Beau ...
- python爬取腾讯新闻_python爬虫实战――爬取腾讯新闻 !
无论我们通过浏览器打开网站.访问网页,还是通过脚本对URL网址进行访问,本质上都是对HTTP服务器的请求,浏览器上所呈现的.控制台所显示的都是HTTP服务器对我们请求的响应. 以打开腾讯新闻官网为例, ...
- python爬虫爬取房源_Python爬虫项目--爬取自如网房源信息
本次爬取自如网房源信息所用到的知识点: 1. requests get请求 2. lxml解析html 3. Xpath 4. MongoDB存储 正文 1.分析目标站点 1. url: http:/ ...
最新文章
- 单张图像重建3D人手、人脸和人体
- 有趣的python项目_推荐个超好玩的Python项目
- python web-Java web 和 Python web??
- 【转】Photoshop网站设计:DesignStudio
- Kotlin的Reified类型:怎样在函数内使用这一类型(KAD 14)
- if some one want to buy it
- 搭建DVWA漏洞环境
- python cls_关于python中的self,ins , cls的解释
- java上传png_java上传png图片出现红色背景
- 2020年排名前20的基于SpringBoot搭建的开源项目,帮你快速进行项目搭建!
- 加入收藏代码_100个原生JavaScript代码片段知识点详细汇总【实践】
- nltk packages下载问题
- 并发的线程入门到并发安全原理解析,offer拿到手软
- 6.4 First Missing Positive --- 图解
- 【图像分割】基于matlab超像素图像分割【含Matlab源码 720期】
- Linux Shell脚本教程(bash)
- mysql dump hbase_导入mysqldump表结构
- html表格的thead标签,thead和tbody标签
- 北京科技大学与北京工业大学计算机,请问北京工业大学和北京科技大学2010年计算机专业研究生的录取分数线是多少?谢谢!...
- ElasticSearch for GIS应用