scrapy案例(附源码)

1.完善豆瓣爬虫,在pipelines.py代码中完善

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import json
import logging

from itemadapter import ItemAdapter
import pymysql


class DoubanPipeline:
    def __init__(self):
        self.file = open('douban.json', 'a', encoding='utf-8')

    def process_item(self, item, spider):
        data = dict(item)
        json_data = json.dumps(data, ensure_ascii=False) + ',\n'
        self.file.write(json_data)
        
         # 不return的情况下,另一个权重较低的pipeline将不会获得item
        return item

    # 整个程序生命周期结束 内存销毁 该方法才会执行结束
    def __del__(self):
        self.file.close()


class DoubansqlPipeline:
    def __init__(self):
        # 连接数据库                 用户名       密码             数据库名               编码
        self.db = pymysql.connect(user='root', password='admin', database='xiaoxiao', charset='utf8')
        self.cursor = self.db.cursor()  # 获取操作游标

    def process_item(self, item, spider):
         # 此时item对象必须是一个字典,再插入,如果此时item是BaseItem则需要先转换为字典:dict(BaseItem)
        item = dict(item)
        # print(item)
        try:
            sql = 'insert into db_data(name,content,link,txt) values(%s,%s,%s,%s)'  # SQL语句
            self.cursor.execute(sql, [item['name'], item['content'], item['link'], item['txt']])  # 执行sql语句
            self.db.commit()  # 提交
        except Exception as e:
            logging.error(f'数据存储异常,原因:{e}')
            
       # 不return的情况下,另一个权重较低的pipeline将不会获得item
        return item

    # 当所属类运行完成 这个方法就会关闭掉
    def close_spider(self, spider):
        self.db.close()

2.开启管道

ITEM_PIPELINES = {
    'douban.pipelines.DoubanPipeline': 300,   # 300表示权重
    'douban.pipelines.DoubansqlPipeline': 301,  # 权重值越小,越优先执行!
}

scrapy.Request发送post请求

我们可以通过scrapy.Request()指定method、body参数来发送post请求;

也可以使用scrapy.FormRequest()来发送post请求

scrapy.FormRequest()能够发送表单和ajax请求,参考阅读

https://www.jb51.net/article/146769.htm

爬虫文件

import scrapy
import json
from jsonpath import jsonpath

class BydSpiderSpider(scrapy.Spider):
    name = 'byd_spider'
    # 1.检查域名
    allowed_domains = ['bydauto.com']
    # 2.修改请求url
    # start_urls = ['https://www.bydauto.com.cn/api/comom/search_join_shop']
    # 注意post请求的起始url发请求的那一刻要求是str类型
    city_url = 'https://www.bydauto.com.cn/api/comom/search_join_shop'
    # post请求的参数
    payload = {"type": 2, "province": 430000, "city": 430100, "network": 'null'}

    # 3,构造起始方法:start_requests(self),此方法是spider模块中的定制方法,是一个重写方法,不能修改名字和参数
    # 作用:爬虫从该方法开始,此时start_urls 和 parse( ) 函数可删除,可在该start_requests函数中写入多种请求
    def start_requests(self):
        # 4.将请求信息打包成一个请求对象 并将返回的响应数据交给parse方法处理
        yield scrapy.Request(url=self.city_url,method='POST',body=json.dumps(self.payload),callback=self.parse)

    # 5.解析比亚迪地址和电话信息
    def parse(self, response):
        json_data = response.json()
        address = jsonpath(json_data,'$..address')
        print(address)
        tel = jsonpath(json_data,'$..tel')
        print(tel)

思路分析

1.找到post的url地址然后定位url地址

2.找到请求体的规律:分析post请求的请求体(参数)

3.start_urls中的url地址是交给parse处理的,如有必要,我们需要重写strat_request这个方法

  • process_item(self,item,spider):实现对item数据的处理
  • open_spider(self,spider):在爬虫开启的时候仅执行一次
  • close_spider(self,spider):在爬虫关闭的时候仅执行一次 

 spider指的是使用这个管道的爬虫,必须return item。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

eqwaak0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值