我想运行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: {}
我希望你能理解我的问题(英文不是我的母语......;)) 在此先感谢!
感谢您的回答!我会尝试在scrapy项目中使用'get_project_settings()'运行我的脚本 – R0rschach
我的蜘蛛正在工作,谢谢! – R0rschach