스크래피 데이터를 텍스트 파일로 내 보내서 파이썬 스크립트가 실행될 때 스크래피를 실행하기 위해 터미널을 거치지 않고 텍스트 파일을 생성하는 방법이 있습니까?
코드 예
class NameListSpider(CrawlSpider):
name = 'namelist'
allowed_domains = ['namelist.com']
start_urls = ['http://www.namelist.com']
rules = (
Rule(LinkExtractor(restrict_xpaths='//div[@class="post-outer"]/a'), callback='parse_item', follow=True),
)
def parse_item(self, response):
yield {
'name': response.xpath('//div[@class="alt"]/span/span[2]/text()').get()
}
# have added the below as an example
with open("file.txt", "a") as file:
file.write(name)
이 결과를 얻을 수있는 방법은 여러 가지가 있습니다.
프로젝트를 실행 scrapy crawl
하려면 설정에서 피드를 구성 할 수 있습니다 .
함께 실행 python your_python_script.py
하려면 설정도 전달해야합니다.
다른 항목을 다른 파일로 내보낼 수도 있습니다. 이를 위해 github에서이 파이프 라인을 확인하세요.
이제 스파이더를 사용하여 실행하려면 python your_script.py
다음과 같이하십시오.
# -*- coding: utf-8 -*-
from scrapy.settings import Settings
from scrapy.crawler import CrawlerRunner
from twisted.internet import reactor
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule, CrawlSpider
class NameListSpider(CrawlSpider):
name = 'namelist'
allowed_domains = ['namelist.com']
start_urls = ['http://www.namelist.com']
rules = (
Rule(LinkExtractor(restrict_xpaths='//div[@class="post-outer"]/a'), callback='parse_item', follow=True),
)
def parse_item(self, response):
yield {
'name': response.xpath('//div[@class="alt"]/span/span[2]/text()').get()
}
def get_settings():
settings = Settings()
settings.set('FEED_URI', 'file.txt')
settings.set('FEED_FORMAT', 'csv')
return settings
if __name__ == '__main__':
settings = get_settings()
runner = CrawlerRunner(settings)
d = runner.crawl(NameListSpider)
d.addBoth(lambda _: reactor.stop())
reactor.run()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다