Python 未按顺序返回BeautifulSoup循环

Python 未按顺序返回BeautifulSoup循环,python,beautifulsoup,Python,Beautifulsoup,返回的结果不按顺序,我需要按顺序返回结果 试图记录排名 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')) 如果要在列表中打印“代码”,只需使用: 您还可以

返回的结果不按顺序,我需要按顺序返回结果

试图记录排名

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'))

如果要在列表中打印“代码”,只需使用:

您还可以改进定位图元的方式,并使用:

这也是一个好主意:

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')]
def parse(self, response):
    soup = BeautifulSoup(response.body)
    return [link.get('code') for link in soup.select('dl#resultList dd')]
soup = BeautifulSoup(response.body, "html.parser")
# or soup = BeautifulSoup(response.body, "html5lib")
# or soup = BeautifulSoup(response.body, "lxml")