간격을두고 새로 고치는 목록에서 한 번에 하나씩 프록시를 가져 오려고합니다. 그 문제는 없습니다.(Mis) Generators 이해
프록시 중 일부는 좋지 않으므로 목록에서 다음 프록시를 사용하고 싶습니다. 이것은 제 생성기가 들어오는 곳입니다. 그러나 처음으로 .next()를 호출하여 생성기 롤링을 얻을 수는 있지만, 두 번째 호출에서는 동일한 값을 얻습니다!
확실히 발전기 작동 방식을 이해하는 데 중요한 부분을 놓치고 있어야합니다.
class ProxyHandler:
def __init__(self):
self.proxies = list()
self.current = dict()
def get_proxies(self):
""" Retrieves proxies """
def __len__(self):
return len(self.proxies)
def yield_proxy(self):
if not self.proxies:
print 'Created new proxy list'
self.get_proxies() # This populates self.proxies which is a list of tuples where the 0th element is the host and the 1st element is the port
for p in self.proxies:
try:
proxy = {'http': 'http://%s:%s' % (p[0], p[1])} # Formatted to python's request lib proxy format
self.current = proxy
yield proxy
except StopIteration:
print 'Reached end of proxy list'
self.current = {}
self.get_proxies()
yield self.yield_proxy()
및 사용 :
이gen = self.proxy_handler.yield_proxy()
gen.next()
새로운 발전기가 시작 :
def get_response(self, url):
proxy = self.proxy_handler.current
if proxy == {}:
proxy = self.proxy_handler.yield_proxy().next()
print 'Current proxy -', proxy
response = url_request(url, proxy=proxy) # url_request() is basically a modified version of python's requests
print response
if response: # url_request() returns true if status code == 200
return response, proxy
gen = self.proxy_handler.yield_proxy()
gen.next()
return self.get_ebay_response(url)
그래서이 문제를 해결하기 위해 내 메서드 외부에서 생성자를 만들고 필요할 때 호출해야합니다. –
@galalmighty : 정확하게. 생성기는 상태를 유지하는 단일 객체입니다. 값을 필요로 할 때마다 교체하지 말고 주변에 두십시오. –
통찰력 있고 자세하며 매우 명확합니다. 고맙습니다! 약 10 분 만에 많은 것을 배웠습니다. –