我正在尝试学习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
答案 0 :(得分:0)
问题是你在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",
]