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 启动程序

相关文章
|
1天前
|
机器学习/深度学习 Python 数据处理
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力负荷数据
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力负荷数据
12 0
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力负荷数据
|
1天前
|
存储 机器学习/深度学习 数据可视化
Python面板时间序列数据预测:格兰杰因果关系检验Granger causality test药品销售实例与可视化
Python面板时间序列数据预测:格兰杰因果关系检验Granger causality test药品销售实例与可视化
39 6
|
2天前
|
机器学习/深度学习 数据采集 供应链
从数据到决策:scikit-learn在业务分析中的应用
【4月更文挑战第17天】本文探讨了scikit-learn在业务分析中的应用,包括数据预处理、分类、回归和聚类模型的构建,以及模型评估与优化。通过使用scikit-learn,企业能有效处理数据、预测趋势、客户细分并制定决策,从而提升经营效率和市场策略。随着机器学习的发展,scikit-learn在业务分析领域的潜力将持续释放,创造更多价值。
|
2天前
|
算法 数据可视化 Python
Python中LARS和Lasso回归之最小角算法Lars分析波士顿住房数据实例
Python中LARS和Lasso回归之最小角算法Lars分析波士顿住房数据实例
10 0
|
2天前
|
BI 开发者 数据格式
Python代码填充数据到word模板中
【4月更文挑战第16天】
|
2天前
|
数据可视化 算法 API
Python数据可视化-seaborn Iris鸢尾花数据
Python数据可视化-seaborn Iris鸢尾花数据
|
3天前
|
程序员 索引 Python
06-python数据容器-set(集合)入门基础操作
06-python数据容器-set(集合)入门基础操作
|
3天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
3天前
|
机器学习/深度学习 数据处理 计算机视觉
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力消耗数据
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力消耗数据
16 1
|
4天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。