Scrapy:在scrapy 中使用SQLAlchemy 有“NameError: name 'connection' is not defined”

他们住

在scrapy中使用SQLAlchemy有NameError,报错信息如下:

Traceback (most recent call last):
  File "e:\weibo_spider\venv\lib\site-packages\twisted\internet\defer.py", line 1386, in _inlineCallbacks
    result = g.send(result)
  File "e:\weibo_spider\venv\lib\site-packages\scrapy\crawler.py", line 79, in crawl
    yield self.engine.open_spider(self.spider, start_requests)
NameError: name 'connection' is not defined

这是我的Scrapy Pipeline课:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from .models import MyModel # my sqlalchemy model


class WeiboSpiderPipeline(object):

    def open_spider(self, spider):
        # using pymysql as the conncetor
        engine = create_engine('mysql+pymysql://root@localhost/wbspider_data')
        Session = sessionmaker(bind=engine)
        self.conn = engine.connect()
        self.session = Session(bind=connection)

    def close_spider(self, spider):
        self.conn.close()

    def process_item(self, item, spider):
        return item

我在命令行中测试模型,它可以工作,但NameError在我运行scrapy crawl myspidername命令发生

帮助!

奥马尔·阿斯加尔

使用这种方法。

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)
session = Session()

# it will send the connection back to the pool of connections in the engine, but it will not close the connection instead it will make the connection idle
session.close()
# to close the engine having pool of connections will close all the idle connections in the pool
engine.dispose()()


# for directing close the connection on session.close, use this code
# Disabling pooling using NullPool:

from sqlalchemy.pool import NullPool
engine = create_engine(
      'postgresql+psycopg2://scott:tiger@localhost/test',
      poolclass=NullPool)
session.close()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

NameError:使用Scrapy时未定义名称“ hxs”

来自分类Dev

如何修复“NameError: name 'context' is not defined”

来自分类Dev

Scrapy + SQLAlchemy + MySQL错误

来自分类Dev

Scrapy:使用scrapy和xpath时,如何同时获取文本和带有<b>标记的文本?

来自分类Dev

在Windows Powershell中使用Scrapy

来自分类Dev

在python中使用scrapy的LinkExtractor

来自分类Dev

带有 Scrapy 的 For 循环

来自分类Dev

使用带有Scrapy的CSS选择器获取href

来自分类Dev

使用Scrapy从具有多个后代的节点中擦除文本

来自分类Dev

使用scrapy刮取没有javascript代码的文本

来自分类Dev

如何使用Scrapy抓取网站所有页面上的链接

来自分类Dev

使用Scrapy进行有效的数据循环

来自分类Dev

使用Scrapy搜寻所有高尔夫球场页面

来自分类Dev

使用scrapy和FormRequest爬行所有页面

来自分类Dev

使用Scrapy下载所有JS文件吗?

来自分类Dev

如何使用Scrapy从网站上获取所有纯文本?

来自分类Dev

使用 Scrapy 抓取所有链接和链接内容

来自分类Dev

使用 Scrapy 选择包含特定属性的所有 Div 的 XPATH

来自分类Dev

使用 python scrapy 没有得到结果

来自分类Dev

使用scrapy丢失数据

来自分类Dev

使用Scrapy的LinkExtractor

来自分类Dev

使用scrapy时出错

来自分类Dev

缓冲管道使用scrapy

来自分类Dev

使用scrapy登录表单

来自分类Dev

使用scrapy爬网

来自分类Dev

使用Scrapy遍历链接

来自分类Dev

使用Selenium + Scrapy

来自分类Dev

使用scrapy抓取项目

来自分类Dev

使用scrapy抓取数据