2016-11-18 75 views
0

我想运行scrapy作为python脚本,但我无法弄清楚如何正确设置设置或我如何提供它们。我不确定这是否是一个设置问题,但我假设它。如何将运行scrapy的默认设置设置为python脚本?

我的配置:

  • Python 2.7版的x86(虚拟环境)
  • Scrapy 1.2.1
  • Win 7的64位

我把建议从https://doc.scrapy.org/en/latest/topics/practices.html#run-scrapy-from-a-script得到它运行。我有以下建议的一些问题:

如果您在Scrapy项目中有一些额外的帮助程序,您可以使用它们在项目中导入这些组件。您可以自动将您的蜘蛛名称传递给CrawlerProcess,并使用get_project_settings通过项目设置获取Settings实例。

那么,“Scrapy项目内”是指什么?当然,我必须导入库并安装依赖项,但我想避免使用scrapy crawl xyz开始抓取过程。

这里的myScrapy.py

from scrapy.crawler import CrawlerProcess 
from scrapy.utils.project import get_project_settings 
from scrapy.spiders import CrawlSpider, Rule 
from scrapy.linkextractors import LinkExtractor 
from scrapy.item import Item, Field 
import os, argparse 


#Initialization of directories 
projectDir = os.path.dirname(os.path.realpath('__file__')) 
generalOutputDir = os.path.join(projectDir, 'output') 

parser = argparse.ArgumentParser() 
parser.add_argument("url", help="The url which you want to scan", type=str) 
args = parser.parse_args() 
urlToScan = args.url 

#Stripping of given URL to get only the host + TLD 
if "https" in urlToScan: 
    urlToScanNoProt = urlToScan.replace("https://","") 
    print "used protocol: https" 
if "http" in urlToScan: 
    urlToScanNoProt = urlToScan.replace("http://","") 
    print "used protocol: http" 

class myItem(Item): 
    url = Field() 

class mySpider(CrawlSpider): 
    name = "linkspider" 
    allowed_domains = [urlToScanNoProt] 
    start_urls = [urlToScan,] 
    rules = (Rule(LinkExtractor(), callback='parse_url', follow=True),) 

    def generateDirs(self): 
     if not os.path.exists(generalOutputDir): 
      os.makedirs(generalOutputDir) 
     specificOutputDir = os.path.join(generalOutputDir, urlToScanNoProt) 
     if not os.path.exists(specificOutputDir): 
      os.makedirs(specificOutputDir) 
     return specificOutputDir 

    def parse_url(self, response): 
     for link in LinkExtractor().extract_links(response): 
      item = myItem() 
      item['url'] = response.url 
     specificOutputDir = self.generateDirs() 
     filename = os.path.join(specificOutputDir, response.url.split("/")[-2] + ".html") 
     with open(filename, "wb") as f: 
      f.write(response.body) 
     return CrawlSpider.parse(self, response) 
     return item 

process = CrawlerProcess(get_project_settings()) 
process.crawl(mySpider) 
process.start() # the script will block here until the crawling is finished 

为什么我要叫process.crawl(mySpider),而不是process.crawl(linkspider)的代码?我认为这是一个设置问题,因为它们设置在“正常”scrapy项目中(您必须运行scrapy crawl xyz),因为输入值为 2016-11-18 10:38:42 [scrapy] INFO: Overridden settings: {} 我希望你能理解我的问题(英文不是我的母语......;)) 在此先感谢!

回答

3

使用脚本(而不是scrapy crawl)运行爬网时,其中一个选项的确使用CrawlerProcess

那么Scrapy项目里面的含义是什么?

是什么意思是,如果你在与scrapy startproject创建scrapy项目,即根目录运行脚本,你必须在scrapy.cfg文件,除其他外[settings]部分。

为什么我必须调用process.crawl(mySpider)而不是process.crawl(linkspider)?

阅读the documentation on scrapy.crawler.CrawlerProcess.crawl() for details

参数:
crawler_or_spidercls(履带例如,蜘蛛子类或字符串) - 已创建的履带式或蜘蛛类或蜘蛛的名字里面的项目创建它

我不知道该框架的一部分,但我怀疑只有一个蜘蛛名 - 我相信你的意思是而不是process.crawl("linkspider"),在scrapy项目之外,scrapy不知道在哪里寻找蜘蛛(它没有提示)。因此,为了告诉scrapy哪个蜘蛛运行,不妨直接给这个类(而不是蜘蛛类的一个实例)。

get_project_settings()是一个辅助,但本质上,CrawlerProcess需要用Settings对象被初始化(见https://docs.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerProcess

事实上,它也接受设置dict(这是internally converted into a Settings instance),如图the example you linked to

process = CrawlerProcess({ 
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' 
}) 

那么根据什么设置,你需要比scrapy默认覆盖,你需要做的是这样的:

process = CrawlerProcess({ 
    'SOME_SETTING_KEY': somevalue, 
    'SOME_OTHERSETTING_KEY': someothervalue, 
    ... 
}) 
process.crawl(mySpider) 
... 
+0

感谢您的回答!我会尝试在scrapy项目中使用'get_project_settings()'运行我的脚本 – R0rschach

+0

我的蜘蛛正在工作,谢谢! – R0rschach