python scrapy框架爬取haozu 数据

简介: 工作中需要数据,刚学习的python 还有 scarpy 如有大神指导,我必虚心学习。

1.创建项目
在控制台通过scrapy startproject 创建项目
我们通过scrapy startproject haozu 创建爬虫项目

haozu

2.创建爬虫文件
在控制台 进入spiders 文件夹下 通过scrapy genspider <网站域名>
scrapy genspider haozu_xzl www.haozu.com 创建爬虫文件

3.在爬虫文件中 haozu_xzl.py写代码 python version=3.6.0

-- coding: utf-8 --

import scrapy
import requests
from lxml import html
etree =html.etree
from ..items import HaozuItem
import random

class HaozuXzlSpider(scrapy.Spider):

# scrapy crawl haozu_xzl
name = 'haozu_xzl'
# allowed_domains = ['www.haozu.com/sz/zuxiezilou/']
start_urls = "http://www.haozu.com/sz/zuxiezilou/"
province_list = ['bj', 'sh', 'gz', 'sz', 'cd', 'cq', 'cs','dl','fz','hz','hf','nj','jian','jn','km','nb','sy',
                 'su','sjz','tj','wh','wx','xa','zz']
def start_requests(self):

    user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'
    headers = {'User-Agent': user_agent}
    for s in self.province_list:
        start_url = "http://www.haozu.com/{}/zuxiezilou/".format(s)
        # 包含yield语句的函数是一个生成器,每次产生一个值,函数被冻结,被唤醒后再次产生一个值
        yield scrapy.Request(url=start_url, headers=headers, method='GET', callback=self.parse, \
                         meta={"headers": headers,"city":s})

def parse(self, response):
    lists = response.body.decode('utf-8')
    selector = etree.HTML(lists)
    elem_list = selector.xpath('/html/body/div[2]/div[2]/div/dl[1]/dd/div[2]/div[1]/a')
    print(elem_list,type(elem_list))
    for elem in elem_list[1:-1]:
        try:
            district = str(elem.xpath("text()"))[1:-1].replace("'",'')
            # district.remove(district[0])
            # district.pop()
            print(district,type(district))
            district_href =str(elem.xpath("@href"))[1:-1].replace("'",'')
            # district_href.remove(district_href[0])
            print(district_href,type(district_href))

            elem_url ="http://www.haozu.com{}".format(district_href)
            print(elem_url)
            yield scrapy.Request(url=elem_url, headers=response.meta["headers"], method='GET', callback=self.detail_url,
                                 meta={"district": district,"url":elem_url,"headers":response.meta["headers"],"city":response.meta["city"]})
        except Exception as e:
            print(e)
            pass
def detail_url(self, response):
    print("===================================================================")
    for i in range(1,50):
        # 组建url
        re_url = "{}o{}/".format(response.meta["url"],i)
        print(re_url)
        try:
            response_elem = requests.get(re_url,headers=response.meta["headers"])
            seles= etree.HTML(response_elem.content)
            sele_list = seles.xpath("/html/body/div[3]/div[1]/ul[1]/li")
            for sele in sele_list:
                href = str(sele.xpath("./div[2]/h1/a/@href"))[1:-1].replace("'",'')
                print(href)
                href_url = "http://www.haozu.com{}".format(href)
                print(href_url)
                yield scrapy.Request(url=href_url, headers=response.meta["headers"], method='GET',
                                     callback=self.final_url,
                                     meta={"district": response.meta["district"],"city":response.meta["city"]})
        except Exception as e:
            print(e)
            pass
def final_url(self,response):
    try:
        body = response.body.decode('utf-8')
        sele_body = etree.HTML(body)
        #获取价格 名称 地址
        item = HaozuItem()
        item["city"]= response.meta["city"]
        item['district']=response.meta["district"]
        item['addr'] = str(sele_body.xpath("/html/body/div[2]/div[2]/div/div/div[2]/span[1]/text()[2]"))[1:-1].replace("'",'')
        item['title'] = str(sele_body.xpath("/html/body/div[2]/div[2]/div/div/div[1]/h1/span/text()"))[1:-1].replace("'",'')
        price = str(sele_body.xpath("/html/body/div[2]/div[3]/div[2]/div[1]/span/text()"))[1:-1].replace("'",'')
        price_danwei=str(sele_body.xpath("/html/body/div[2]/div[3]/div[2]/div[1]/div/div/i/text()"))[1:-1].replace("'",'')
        print(price+price_danwei)
        item['price']=price+price_danwei
        yield item
    except Exception as e:
        print(e)
        pass  

4.修改items.py 文件

-- coding: utf-8 --

Define here the models for your scraped items

See documentation in:

https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class HaozuItem(scrapy.Item):

# define the fields for your item here like:
# name = scrapy.Field()
city = scrapy.Field()
district =scrapy.Field()
title = scrapy.Field()
addr =scrapy.Field()
price = scrapy.Field()

5修改settings.py

打开
ITEM_PIPELINES = {
'haozu.pipelines.HaozuPipeline': 300,
}

6 修改pipelines.py文件 这里可以自定义存储文件格式

-- coding: utf-8 --

Define your item pipelines here

Don't forget to add your pipeline to the ITEM_PIPELINES setting

See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import csv

class HaozuPipeline(object):

def process_item(self, item, spider):
    f = open('./xiezilou2.csv', 'a+',encoding='utf-8',newline='')
    write = csv.writer(f)
    write.writerow((item['city'],item['district'],item['addr'],item['title'],item['price']))
    print(item)
    return item

7.启动框架

在控制台 输入 scrapy crawl haozu_xzl 启动程序

相关文章
|
11天前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
【4月更文挑战第9天】本文对比了Python三大Web框架Django、Flask和Pyramid。Django功能全面,适合快速开发,但学习曲线较陡;Flask轻量灵活,易于入门,但默认配置简单,需自行添加功能;Pyramid兼顾灵活性和可扩展性,适合不同规模项目,但社区及资源相对较少。选择框架应考虑项目需求和开发者偏好。
|
30天前
|
数据采集 数据挖掘 调度
异步爬虫实践攻略:利用Python Aiohttp框架实现高效数据抓取
本文介绍了如何使用Python的Aiohttp框架构建异步爬虫,以提升数据抓取效率。异步爬虫利用异步IO和协程技术,在等待响应时执行其他任务,提高效率。Aiohttp是一个高效的异步HTTP客户端/服务器框架,适合构建此类爬虫。文中还展示了如何通过代理访问HTTPS网页的示例代码,并以爬取微信公众号文章为例,说明了实际应用中的步骤。
|
5天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。
|
6天前
|
关系型数据库 数据库 开发者
Python中的Peewee框架:轻量级ORM的优雅之旅
【4月更文挑战第13天】在Python的众多ORM框架中,Peewee以其轻量级、简洁和易于上手的特点,受到了许多开发者的青睐。Peewee的设计理念是“小而美”,它提供了基本的ORM功能,同时保持了代码的清晰和高效。本文将深入探讨Peewee的核心概念、使用场景以及实战应用,帮助读者更好地理解和使用这一框架。
|
6天前
|
SQL API 数据库
Python中的SQLAlchemy框架:深度解析与实战应用
【4月更文挑战第13天】在Python的众多ORM(对象关系映射)框架中,SQLAlchemy以其功能强大、灵活性和易扩展性脱颖而出,成为许多开发者首选的数据库操作工具。本文将深入探讨SQLAlchemy的核心概念、功能特点以及实战应用,帮助读者更好地理解和使用这一框架。
|
8天前
|
网络协议 Java API
Python网络编程基础(Socket编程)Twisted框架简介
【4月更文挑战第12天】在网络编程的实践中,除了使用基本的Socket API之外,还有许多高级的网络编程库可以帮助我们更高效地构建复杂和健壮的网络应用。这些库通常提供了异步IO、事件驱动、协议实现等高级功能,使得开发者能够专注于业务逻辑的实现,而不用过多关注底层的网络细节。
|
21天前
|
前端开发 JavaScript 数据管理
描述一个使用Python开发Web应用程序的实际项目经验,包括所使用的框架和技术栈。
使用Flask开发Web应用,结合SQLite、Flask-SQLAlchemy进行数据管理,HTML/CSS/JS(Bootstrap和jQuery)构建前端。通过Flask路由处理用户请求,模块化代码提高可维护性。unittest进行测试,开发阶段用内置服务器,生产环境可选WSGI服务器或容器化部署。实现了用户注册登录和数据管理功能,展示Python Web开发的灵活性和效率。
14 4
|
30天前
|
存储 数据库连接 数据处理
Python语言的程序框架
Python语言的程序框架
|
1月前
|
数据采集 存储 数据处理
使用Python爬取豆瓣电影影评:从数据收集到情感分析
本文演示如何使用Python爬虫获取豆瓣电影《肖申克的救赎》的影评数据并进行情感分析。首先,安装requests、BeautifulSoup、pandas和TextBlob库。接着,编写爬虫抓取评论的用户名、评分和内容,存储为DataFrame。然后,利用TextBlob进行情感分析,得到情感分数。此方法有助于分析用户对电影的反馈。
66 1
|
1月前
|
存储 Linux 调度
太好用了!Python 定时任务调度框架 APScheduler 详解!
太好用了!Python 定时任务调度框架 APScheduler 详解!