[英]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.