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

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.

Related

scrapyd deployed in KubeSphere,and when running scrapy selenium got exception:'twisted.internet.error.ReactorAlreadyInstalledError'

I deploy scrapyd in KubeSphere, I got expectation when I run scrapy and selenium:
2022-03-16T12:57:15+0000 [Launcher,1832/stderr] return Crawler(spidercls, self.settings, init_reactor=True)
File "/usr/local/lib/python3.9/site-packages/scrapy/crawler.py", line 82, in __init__
default.install()
File "/usr/local/lib/python3.9/site-packages/twisted/internet/epollreactor.py", line 256, in install
2022-03-16T12:57:15+0000 [Launcher,1832/stderr] installReactor(p)
File "/usr/local/lib/python3.9/site-packages/twisted/internet/main.py", line 32, in installReactor
2022-03-16T12:57:15+0000 [Launcher,1832/stderr] raise error.ReactorAlreadyInstalledError("reactor already installed")
twisted.internet.error.ReactorAlreadyInstalledError: reactor already installed
I don't have twisted installed separately. Why does it report that it already exists?
Without code and package version, it is hard to guess what happens. If your program was once working, check your scrapy version. There is an issue in latest 2.6 version. You could pin your scrapy at 2.5.1 .
If you are under developing scrapy scripts, you might want to run multiple spiders in a script. It is easy to mess up the pipeline and get twisted.internet.error.ReactorAlreadyInstalledError error. You could check this.

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

Is it possible to link to the scrapy docs using intersphinx?

I'm trying to link to the Scrapy documentation using intersphinx, but it does not appear to work.
I have the entry:
'scrapy': ('https://docs.scrapy.org/en/latest/index.html', None)
in my intersphinx_mapping, but I get an error when building my docs saying:
intersphinx inventory 'https://docs.scrapy.org/en/latest/index.html/objects.inv' not fetchable due to <class 'requests.exceptions.HTTPError'>: 404 Client Error: Not Found for url: https://docs.scrapy.org/en/latest/index.html/objects.inv
Obviously this is not the correct link to use (or there isn't one).
I find it strange, because I also have w3lib in my intersphinx_mapping. w3lib is a scrapy subproject and it works just fine. So, I find it strange that intersphinx is possible with a subproject of scrapy, but not with the main project itself.

How to use selenium in pandas to read a webpage?

I want to collect the information of a webpage using chromedriver. How do I install it and use it?
You have to install selenium first if you don't have it already. Then to use selenium:
from selenium.webdriver import Chrome
url="URL of the webpage you want to read"
setting up the driver
webdriver = "path of the chromedriver.exe file saved in your pc"
driver.get(url)
using css selector
y = driver.find_element_by_css_selector('css selector of the data you want to read from the webpage').text
print(y)
You don't install the chromedriver - you download the .exe (from here) and use the path to it in webdriver.Chrome(). This getting started page has a comprehensive guide:
from selenium import webdriver
driver = webdriver.Chrome('/path/to/chromedriver') # refers to the path where you saved the exe
driver.get('http://www.google.com/');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()
Note: download the .exe that matches with your version of chrome!
(In Help > About Google Chrome)
As mentioned by #Patha_Mondal, you need to download the driver and select the elements you want to read. However, as your original question asks "How to use selenium in pandas to read a webpage?", I would say instead consider using Scrapy along with Selenium to create a ".csv" file from the Webpage Data.
Read the ".csv" data into pandas using pandas.read_csv() .
The data from the Webpage might not be clean or properly formatted. Using Scrapy to create a dataset out of it would be beneficial for reading it into pandas. Avoid using pandas directly in the same script as Selenium and Scrapy.
Hope it Helped.

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!