2016-11-28 8 views
1

返される結果が順不同であるため、結果を順番に返す必要があります。BeautifulSupループがシーケンスで返されない

ランキングを記録しようとしています。

def parse(self, response): 
    sourceHtml = BeautifulSoup(response.body) 
    soup = sourceHtml.find("dl", {"id": "resultList"}) 
    for link in soup.find_all('dd'): 
     print(link.get('code')) 

答えて

1

あなただけ"list comprehension"を使用し、リスト内で印刷された「コード」を持つようにしたい場合:

def parse(self, response): 
    sourceHtml = BeautifulSoup(response.body) 
    soup = sourceHtml.find("dl", {"id": "resultList"}) 
    return [link.get('code') for link in soup.find_all('dd')] 

また、あなたは要素を検索し、CSS selectorを使用する方法を改善することができます

def parse(self, response): 
    soup = BeautifulSoup(response.body) 
    return [link.get('code') for link in soup.select('dl#resultList dd')] 

またprovide an underlying parser explicitlyに良いアイデアです:

soup = BeautifulSoup(response.body, "html.parser") 
# or soup = BeautifulSoup(response.body, "html5lib") 
# or soup = BeautifulSoup(response.body, "lxml") 
関連する問題