running scrapy CrawlerProcess as async - scrapy

i would like to run scrapy along with another asyncio script in the same file, but am unable to.
(using the asyncio reactor in the settings:
# TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor")
asyncio.run(playwright_script())
process = CrawlerProcess(get_project_settings())
process.crawl(TestSpider)
process.start()
this raises the error:
RuntimeError: There is no current event loop in thread 'MainThread'.
i'm guessing because the previous run command blocks the event loop?
i have tried to add the scrapy commands into a coroutine like so:
async def run_scrapy():
process = CrawlerProcess(get_project_settings())
process.crawl(TestSpider)
process.start()
asyncio.run(run_scrapy_script())
but receive the error:
RuntimeError: This event loop is already running
How do i properly configure the scrapy CrawlerProcess to run on my asyncio loop?

Related

How to run Scrapy spiders in Celery

There are several posts regarding how to setup Scrapy within a Celery task avoiding to restart the Twister reactor to prevent the twisted.internet.error.ReactorNotRestartable error. I have tried using CrawlerRunner as recommended on docs and crochet but to make it work the following lines have to be removed from the code:
d.addBoth(lambda _: reactor.stop())
reactor.run() # Script blocks here until spider finishes.
This is the full code:
from scrapy.crawler import CrawlerRunner
#app.task(bind=True, name="run_spider")
def run_spider(self, my_spider_class, my_spider_settings):
from crochet import setup
setup() # Fixes the issue with Twisted reactor.
runner = CrawlerRunner(my_spider_settings)
crawler = runner.create_crawler(my_spider_class)
runner.crawl(crawler)
d = runner.join()
def spider_finished(_): <-- This function is called when spider finishes.
logger.info("{} finished:\n{}".format(
spider_name,
json.dumps(
crawler.stats.spider_stats.get(spider_name, {}),
cls=DjangoJSONEncoder,
indent=4
)
))
d.addBoth(spider_finished)
return f"{spider_name} started" <-- How to block execution until spider finishes?
Now works but the Spider seems to be running detached from the task, so I get the return response before the spider is finished. I have used a workaround with the callback spider_finished() but is not ideal because the celery worker keeps running an executing other tasks and eventually kills the process affecting the detached spiders.
Is there a way to block the execution of the task until the Scrapy spider is done?
From doc:
It’s recommended you use CrawlerRunner instead of CrawlerProcess if
your application is already using Twisted and you want to run Scrapy
in the same reactor.
Celery does not use a reactor, so u cant use CrawlerRunner.
Run a Scrapy spider in a Celery Task

I typed `scrapy version` but it trigger or load other spiders in the folder

I'm relatively new to Scrapy, I just type scrapy version like below;
But it did trigger spiders in the folder.
Obviously, I have some spiders in development, for example one spider opens a Chrome web driver in the init method, just typing Scrapy version opens the Chrome browser. Why Scrapy is loading all the spiders in the folder? How to avoid this?
(django_corp_data):~/sherlockit$ scrapy version
['version']
corp_data.spiders.quote
version
Scrapy 1.8.0
I think I made a rookie mistake.
I created the spider using the following command scrapy genspider quotes quotes.com
The above command will create your spider as class QuotesSpider(scrapy.Spider)
If you just type scrapy version or scrapy crawl the scrapy framework will load all your scrapy.Spider classed spiders.
If you are building multiple spiders, create your spider using scrapy crawl template, like scrapy genspider -t crawl quotes quotes.com notice the class of your newly created spider. class QuotesSpider(CrawlSpider)
It took me about a day to figure the above, hope this will help someone.

Scrapy Downloading Files Error

I'm using the files pipeline in Scrapy to download subtitle files off of http://opensubtitles.org.
I've got a list of all the http://dl.opensubtitles.org links, and my spider follows these links and sends the urls to the pipeline.
It works to start, and I can download the first ~100 files without any issue.
However, around then the links seem to create the error:
2016-06-09 11:44:02 [scrapy] WARNING: File (code: 301): Error downloading file from http://dl.opensubtitles.org/en/download/vrf-108d030f/sub/24617> referred in
Does it have something to do with my code?
These are in my settings:
ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
FILES_STORE = 'C:/Users/Rohan/Documents/Fitroom/subtitles/subFiles'
This is my pipeline:
class SubtitlesPipeline(object):
def process_item(self, item, spider):
return item
Thanks!
This error maybe occurred due to download time out, because file maybe bigger in size. Increase download time out.
Try this in setting.py file
DOWNLOAD_TIMEOUT = 500

Run a Scrapy spider in a Celery Task

This is not working anymore, scrapy's API has changed.
Now the documentation feature a way to "Run Scrapy from a script" but I get the ReactorNotRestartable error.
My task:
from celery import Task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
from .spiders import MySpider
class MyTask(Task):
def run(self, *args, **kwargs):
spider = MySpider
settings = get_project_settings()
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
reactor.run()
The twisted reactor cannot be restarted. A work around for this is to let the celery task fork a new child process for each crawl you want to execute as proposed in the following post:
Running Scrapy spiders in a Celery task
This gets around the "reactor cannot be restart-able" issue by utilizing the multiprocessing package. But the problem with this is that the workaround is now obsolete with the latest celery version due to the fact that you will instead run into another issue where a daemon process can't spawn sub processes. So in order for the workaround to work you need to go down in celery version.
Yes, and the scrapy API has changed. But with minor modifications (import Crawler instead of CrawlerProcess). You can get the workaround to work by going down in celery version.
The Celery issue can be found here:
Celery Issue #1709
Here is my updated crawl-script that works with newer celery versions by utilizing billiard instead of multiprocessing:
from scrapy.crawler import Crawler
from scrapy.conf import settings
from myspider import MySpider
from scrapy import log, project
from twisted.internet import reactor
from billiard import Process
from scrapy.utils.project import get_project_settings
from scrapy import signals
class UrlCrawlerScript(Process):
def __init__(self, spider):
Process.__init__(self)
settings = get_project_settings()
self.crawler = Crawler(settings)
self.crawler.configure()
self.crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
self.spider = spider
def run(self):
self.crawler.crawl(self.spider)
self.crawler.start()
reactor.run()
def run_spider(url):
spider = MySpider(url)
crawler = UrlCrawlerScript(spider)
crawler.start()
crawler.join()
Edit: By reading the celery issue #1709 they suggest to use billiard instead of multiprocessing in order for the subprocess limitation to be lifted. In other words we should try billiard and see if it works!
Edit 2: Yes, by using billiard, my script works with the latest celery build! See my updated script.
The Twisted reactor cannot be restarted, so once one spider finishes running and crawler stops the reactor implicitly, that worker is useless.
As posted in the answers to that other question, all you need to do is kill the worker which ran your spider and replace it with a fresh one, which prevents the reactor from being started and stopped more than once. To do this, just set:
CELERYD_MAX_TASKS_PER_CHILD = 1
The downside is that you're not really using the Twisted reactor to its full potential and wasting resources running multiple reactors, as one reactor can run multiple spiders at once in a single process. A better approach is to run one reactor per worker (or even one reactor globally) and don't let crawler touch it.
I'm working on this for a very similar project, so I'll update this post if I make any progress.
To avoid ReactorNotRestartable error when running Scrapy in Celery Tasks Queue I've used threads. The same approach used to run Twisted reactor several times in one app. Scrapy also used Twisted, so we can do the same way.
Here is the code:
from threading import Thread
from scrapy.crawler import CrawlerProcess
import scrapy
class MySpider(scrapy.Spider):
name = 'my_spider'
class MyCrawler:
spider_settings = {}
def run_crawler(self):
process = CrawlerProcess(self.spider_settings)
process.crawl(MySpider)
Thread(target=process.start).start()
Don't forget to increase CELERYD_CONCURRENCY for celery.
CELERYD_CONCURRENCY = 10
works fine for me.
This is not blocking process running, but anyway scrapy best practice is to process data in callbacks. Just do this way:
for crawler in process.crawlers:
crawler.spider.save_result_callback = some_callback
crawler.spider.save_result_callback_params = some_callback_params
Thread(target=process.start).start()
I would say this approach is very inefficient if you have a lot of tasks to process.
Because Celery is threaded - runs every task within its own thread.
Let's say with RabbitMQ as a broker you can pass >10K q/s.
With Celery this would potentially cause to 10K threads overhead!
I would advise not to use celery here. Instead access the broker directly!

PyInstaller --onefile throws Qt error with pandas, matplotlib and sklearn

Using PyInstaller with the --onefile flag, I can successfully build the following script into a .exe:
import sys
from PyQt4 import QtGui
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.statusBar().showMessage('Ready')
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Statusbar')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I get the warnings below when building: (for readability I use "PYINSTALLERDIR" to replace the full path, which is "C:\Users\name\Downloads\pyinstaller-pyinstaller-v2.0-544-g337ae69\pyinstaller-pyinstaller-337ae69\".
PYINSTALLERDIR>pyinstaller.py --onefile --log-level=WARN MainWindowHello.py
1306 WARNING: library python%s%s required via ctypes not found
1468 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable
2957 WARNING: library python%s%s required via ctypes not found
But the outputted 14 MB .exe runs fine and displays a Qt window. However, when I try to add pandas, matplotlib or sklearn, I run into problems with Qt.
Adding either import matplotlib or import sklearn to line 3 of my script gives me these warnings when building:
PYINSTALLERDIR>python pyinstaller.py --onefile --log-level=WARN MainWindowHello.py
1371 WARNING: library python%s%s required via ctypes not found
1528 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable
3051 WARNING: library python%s%s required via ctypes not found
27108 INFO: Adding Microsoft.VC90.MFC to dependent assemblies of final executable
33329 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
When I try to run the resulting .exe (44 MB for matplotlib, 87 MB for sklearn), no Qt window is displayed and I get this error message:
WARNING: file already exists but should not: C:\Users\name\AppData\Local\Temp\_MEI75002\Include\pyconfig.h
Traceback (most recent call last):
File "<string>", line 2 in <module>
File "PYINSTALLERDIR\PyInstaller\loader\pyi_importers.py", line 409, in load_module
ImportError: could not import module 'PySide.QtCore'
With import pandas at line 3, I get the same warnings (as well as warnings about libzmq.pyd, but I have gotten them earlier with working programs). When I try to run the 119 MB .exe, the program crashes and throws the following error:
WARNING: file already exists but should not: C:\Users\name\AppData\Local\Temp\_MEI85162\include\pyconfig.h
Sub class of QObject not inheriting QObject!? Crash will happen when using Example.
I have tried with both PyInstaller 2.0 and the dev version. All three scenarios work well when using the default --onedir instead of --onefile. Can anyone help me figure out what goes awry when using --onefile?
UPDATE: I tried building with pandas in PyInstaller 2.1 and I still get the same error when using --onefile. Again, everything works when not using --onefile.
I was having the same issue with a script where I was importing PyQt4 as well as some modules that were importing PySide. PyInstaller worked fine with the --onedir option (the default), but I was getting ImportError: could not import module 'PySide.QtCore' when using the --onefile option.
After reading this I tried adding 'PySide' as an exclude in my spec file to force exclusive use of PyQt4 and the exe now runs fine. The modules you've listed should work fine with PyQt4 so it should hopefully solve your issue too.
Also, while it's not a huge problem, a solution to the file already exists warning is described here. Just add these lines in the spec file after a = Analysis... to remove the duplicate that causes the warning:
for d in a.datas:
if 'pyconfig' in d[0]:
a.datas.remove(d)
break