繁体   English   中英

python-在函数中创建列表

[英]python - create list in function

我正在尝试学习python并使用下面的脚本,但是我想使用结果创建一个可以在函数外部调用的列表。 当我打印清单时,将产生正确的结果。 print x不执行任何操作。

import requests
from bs4 import BeautifulSoup
import urllib
import re

def hits_one_spider():
    #page = 1
    #while page <= max_pages:
        url = "http://www.siriusxm.ca/hits-1-weekend-countdown/"
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.find('div', {'class': 'entry-content'}).findAll('li'):
            #href = "http://www.siriusxm.ca/" + link.get('href')
            title = link.string
            #print(href)
            #print(title)
            return list

x = hits_one_spider()

print x

问题是您在for循环中说了return list 因此,它在第一次迭代后返回。 而且,通过这样做,您实际上并没有将其作为列表返回。

相反,您的情况是这样的:

lst = []
for link in soup.find('div', {'class': 'entry-content'}).findAll('li'):
    lst.append(link.string)
return lst

这将导致返回(并打印)包含以下内容的列表:

[
    "Sam Smith – Stay With Me",
    "Kongos – Come With Me Now",
    "Iggy Azalea – Fancy feat. Charli XCX",
    "OneRepublic – Love Runs Out",
    "Magic! – Rude",
    ... and a lot more ...
    "Oh Honey – Be Okay",
    "Katy Perry – Birthday",
    "Neon Trees – Sleeping With A Friend",
    "Cher Lloyd – Sirens",
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM