2015-01-02 3 views
0

나는 꽤 오랫동안 이것을 디버깅 해왔고, 나는 왜 내가 원하는대로 append 메소드를 얻을 수 없는지 잘 모르겠다. 이제는 데이터를 가져 오는 웹 사이트 (espn)의 각 플레이어 항목으로 이동하여 내 선수 1 배열에 저장하고 싶습니다. 인쇄 할 때 (재생할 때) 15 개의 다른 플레이어 항목이 표시되지만, 플레이어 1 배열에 추가 한 다음 루프가 끝날 때까지 반환하면 15 번 이상 마지막 (또는 첫 번째) 플레이어 만 표시됩니다. 너희들이 내 코드의 나머지 부분을 참조 바로 알려 주시기 내가 업로드하겠습니다하려면내 Sciac 콜백 함수와 관련된 문제

def parseRoster(self, response): 
    play = response.meta['play'] 
    players1 = [] 
    int = 0 
    for players in response.xpath("//td[@class='sortcell']"): 
     play['name'] = players.xpath("a/text()").extract()[0] 
     play['position'] = players.xpath("following-sibling::td[1]").extract()[0] 
     play['age'] = players.xpath("following-sibling::td[2]").extract()[0] 
     play['height'] = players.xpath("following-sibling::td[3]").extract()[0] 
     play['weight'] = players.xpath("following-sibling::td[4]").extract()[0] 
     play['college'] = players.xpath("following-sibling::td[5]").extract()[0] 
     play['salary'] = players.xpath("following-sibling::td[6]").extract()[0] 
     print(play) 
     players1.append(play) 
    print(players1) 
    return players1 

, 내가 요청 객체 & 내가 요청 객체를 선언 한 직후 메타 방법을 채울 수 있도록해야합니까 내 주요 코드에서.

편집 : 또한 테이블에 빈 항목이 많기 때문에 1 목록 (기본적으로 추출의 끝에서 [0]에 대한 이유)으로 모든 데이터를 추출하지 않은 이유 중 하나입니다. 당겨서이 방법을 사용하면 데이터베이스에 쉽게 보낼 수 있습니다.

Edit1 : 좋아요. 좋아요. 그래서 print (players1)를 for 루프 안에 넣고 루프가 어떻게 든 최신 플레이어 이름으로 빈 배열을 덮어 쓰는 것을보고 있습니다. 이제는 이전과 같은 방식으로 사용했기 때문에 이것이 왜 그런지 잘 모르겠습니다.

답변

1

이전 콜백에서 만든 Item 인스턴스를 play = response.meta['play'] 참조로 가정합니다.

루프는 for players in ... 루프에서 동일한 인스턴스를 다시 작성하고 동일한 인스턴스를 15 번 추가합니다. 동일한 파이썬 객체의 15 배 목록을 작성하고 있습니다.

각 루프 반복마다이 play 인스턴스를 response.meta에서 복사 한 다음 다른 필드를 설정해야합니다. 이 같은 것이 작동해야합니다 :

def parseRoster(self, response): 
    play_original = response.meta['play'] 
    players1 = [] 
    int = 0 
    for players in response.xpath("//td[@class='sortcell']"): 

     play = play_original.copy() 

     play['name'] = players.xpath("a/text()").extract()[0] 
     play['position'] = players.xpath("following-sibling::td[1]").extract()[0] 
     play['age'] = players.xpath("following-sibling::td[2]").extract()[0] 
     play['height'] = players.xpath("following-sibling::td[3]").extract()[0] 
     play['weight'] = players.xpath("following-sibling::td[4]").extract()[0] 
     play['college'] = players.xpath("following-sibling::td[5]").extract()[0] 
     play['salary'] = players.xpath("following-sibling::td[6]").extract()[0] 
     print(play) 
     players1.append(play) 
    print(players1) 
    return players1 
+0

나는 play_original.copy가 중요한 점에 대해 여전히 혼란스러워합니다. 사실 play_original이 어디서 업데이트되었는지는 확실치 않습니다. 나에게 유일한 시간 재생은 for 루프에있다. 내 마음에 : 은 - 플레이는 플레이어 1 배열 (일명리스트)의 말에, 내가 근근이 살아가고있어 이름 값 쌍의 집합을 추가 - - 플레이 아이템은 임시 사전 입니다 그것은 하나의 플레이어 선택 긁어 된 후에는 , 다음으로 이동하고 다음 재생 항목이 players1 목록에 추가됩니다. 15 개의 인스턴스 목록을 작성한 것을 보지 못했습니다. – user3042850

관련 문제