我正在使用requests
和bs4
import requests
from bs4 import BeautifulSoup as bs
r = requests.get("http://xml.skiddlecdn.co.uk/xml/affiliates/topsellers.xml")
if r.status_code == 200:
data = bs(r.text, 'xml')
raw_dates = data.find_all('date')
dates = [date.string for date in raw_dates]
for date in sorted(dates):
print("{}. {}".format(i for i in range(1, len(dates))), date))
else:
r.raise_for_status()
我的预期结果:
1. 2017-01-17
2. 2017-01-20
3. 2017-01-20
# etc...
我的实际结果:
<generator object <genexpr> at 0x06022B70>. 2017-01-17
<generator object <genexpr> at 0x06022B70>. 2017-01-20
<generator object <genexpr> at 0x06022B70>. 2017-01-20
# etc...
为什么?
答案 0 :(得分:3)
它打印一个生成器,因为你传递了一个生成器。我假设您只想显示带有索引值的日期。为什么不使用enumerate
?
for i, date in enumerate(sorted(dates), 1):
print("{}. {}".format(i, date))