[英]python - create list in function
I am trying to learn python and have the below script that works, but I want to use the results to create a list that I can call outside the function. 我正在尝试学习python并使用下面的脚本,但是我想使用结果创建一个可以在函数外部调用的列表。 When I print list the right results are produced. 当我打印清单时,将产生正确的结果。 The print x
does nothing. 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
The problem is that you say return list
in the for loop. 问题是您在for循环中说了return list
。 Thus it returns after the first iteration. 因此,它在第一次迭代后返回。 Further you aren't actually returning it as a list, by doing it like that. 而且,通过这样做,您实际上并没有将其作为列表返回。
What you instead what is something like this: 相反,您的情况是这样的:
lst = []
for link in soup.find('div', {'class': 'entry-content'}).findAll('li'):
lst.append(link.string)
return lst
Which results in returning (and printing) a list containing: 这将导致返回(并打印)包含以下内容的列表:
[
"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.