मैं अजगर और स्क्रैपी के लिए नया हूं, कुछ udemy और youtube ट्यूटोरियल देखे हैं और अब अपना पहला उदाहरण आजमा रहे हैं। मुझे पता है कि लूप कैसे करें, अगर कोई अगला बटन है। लेकिन मेरे मामले में ऐसा कोई नहीं है।
यहां मेरा कोड है, जो किसी एक यूआरएल पर काम कर रहा है, लेकिन स्टार्ट यूआरएल को बाद में बदलने की जरूरत है:
class Heroes1JobSpider(scrapy.Spider):
name = 'heroes1_job'
# where to extract
allowed_domains = ['icy-veins.com']
start_urls = ['https://www.icy-veins.com/heroes/alarak-build-guide']
def parse(self, response):
#what to extract
hero_names = response.xpath('//span[@class="page_breadcrumbs_item"]/text()').extract()
hero_buildss = response.xpath('//h3[@class="toc_no_parsing"]/text()').extract()
hero_buildskillss = response.xpath('//span[@class="heroes_build_talent_tier_visual"]').extract()
for item in zip(hero_names, hero_buildss, hero_buildskillss):
new_item = Heroes1Item()
new_item['hero_name'] = item[0]
new_item['hero_builds'] = item[1]
new_item['hero_buildskills'] = item[2]
yield new_item
लेकिन यह केवल एक हीरो है, और मुझे उनमें से लगभग 90 चाहिए। प्रत्येक url नायक के नाम पर निर्भर करता है। मैं इस आदेश द्वारा यूआरएल की सूची प्राप्त कर सकता हूं:
start_urls = ['https://www.icy-veins.com/heroes/assassin-hero-guides')
...
response.xpath('//div[@class="nav_content_block_entry_heroes_hero"]/a/@href').extract()
लेकिन मुझे नहीं पता कि पार्स फ़ंक्शन को उन पर लूप करने के लिए इस सूची को कैसे स्टोर किया जाए।
अग्रिम में धन्यवाद!
1 उत्तर
क्या उन्हें parse
फ़ंक्शन में पार्स करना महत्वपूर्ण है? आप अपनी नायक सूची को एक फ़ंक्शन में पार्स कर सकते हैं और फिर इस सूची को नायक डेटा को इस तरह से स्क्रैप करने के लिए पुन: सक्रिय कर सकते हैं:
from scrapy import Request
...
start_urls = ['https://www.icy-veins.com/heroes/assassin-hero-guides')
def parse(self, response):
heroes_xpath = '//div[@class="nav_content_block_entry_heroes_hero"]/a/@href'
for link in response.xpath(heroes_xpath).extract():
yield Request(response.urljoin(link), self.parse_hero)
def parse_hero(self, response):
# copying your method here
hero_names = response.xpath('//span[@class="page_breadcrumbs_item"]/text()').extract()
hero_buildss = response.xpath('//h3[@class="toc_no_parsing"]/text()').extract()
hero_buildskillss = response.xpath('//span[@class="heroes_build_talent_tier_visual"]').extract()
for item in zip(hero_names, hero_buildss, hero_buildskillss):
new_item = Heroes1Item()
new_item['hero_name'] = item[0]
new_item['hero_builds'] = item[1]
new_item['hero_buildskills'] = item[2]
yield new_item