![](/img/trans.png)
[英]Python yield (migrating from Ruby): How can I write a function without arguments and only with yield to do prints?
[英]How do I obtain results from 'yield' in python?
也許 Python 的yield
對某些人來說是補救措施,但對我來說不是……至少現在還沒有。 我了解yield
創建了一個“發電機”。
當我決定學習 scrapy 時,我偶然發現了yield
。 我為 Spider 編寫了一些代碼,其工作方式如下:
import scrapy
class newSpider(scrapy.Spider)
name = 'new'
allowed_domains = ['www.alloweddomain.com']
start_urls = ['https://www.alloweddomain.com']
def parse(self, response)
links = response.xpath('//a/@href').extract()
for link in links:
if link == 'SpecificCriteria':
next_link = response.urljoin(link)
yield Request(next_link, callback=self.parse_new)
編輯1:
for uid_dict in self.parse_new(response):
print(uid_dict['uid'])
break
結束編輯 1
在此處運行代碼會將response
評估為 HTTP 對start_urls
的響應,而不是對next_link
的響應。
def parse_new(self, response)
trs = response.xpath("//*[@class='unit-directory-row']").getall()
for tr in trs:
if 'SpecificText' in tr:
elements = tr.split()
for element in elements:
if 'onclick' in element:
subelement = element.split('(')[1]
uid = subelement.split(')')[0]
print(uid)
yield {
'uid': uid
}
break
它起作用了,scrapy 抓取第一頁,創建新的超鏈接並導航到下一頁。 new_parser 為 uid 解析 HTML 並“生成”它。 scrapy的引擎顯示正確的uid是'yielded'。
我不明白的是如何“使用”由 parse_new 獲得的 uid 來創建和導航到新的超鏈接,就像我想要一個變量一樣,我似乎無法使用Request
返回一個變量。
我會檢查“yield”關鍵字的作用是什么? 很好地解釋了yield
的工作原理。
同時, spider.parse_new(response)
是一個可迭代的 object。 也就是說,您可以通過for
循環獲取其產生的結果。 例如,
for uid_dict in spider.parse_new(response):
print(uid_dict['uid'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.