我正在尝试编写的函数遇到了一些麻烦。它应该做的是 1) 转到特定 URL 并获取存储在特定 div 中的金融部门列表;2)访问每个部门各自的页面并从中获取3条特定信息;3) 将收集到的集合放入字典中;和 4) 将该字典附加到另一个字典。
所需的输出是一个字典,其中包含所有部门的字典列表。
这是我的功能:
def fsr():
fidelity_sector_report = dict()
url = "https://eresearch.fidelity.com/eresearch/goto/markets_sectors/landing.jhtml"
import requests
from bs4 import BeautifulSoup
# scrape the url page and locate links for each sector
try:
response = requests.get(url)
if not response.status_code == 200:
return 'Main page error'
page = BeautifulSoup(response.content, "lxml")
sectors = page.find_all('a',class_="heading1")
for sector in sectors:
link = 'https://eresearch.fidelity.com/' + sector['href']
name = sector.text
sect = dict()
lst = []
# scrape target pages for required information
try:
details = requests.get(link)
if not details.status_code == 200:
return 'Details page error'
details_soup = BeautifulSoup(details.content,'lxml')
fundamentals = details_soup.find('div',class_='sec-fundamentals')
values = dict()
#locate required values by addressing <tr> text and put them in a dictionary
values['Enterprise Value'] = fundamentals.select_one('th:contains("Enterprise Value") + td').text.strip()
values['Return on Equity (TTM)'] = fundamentals.select_one('th:contains("Return on Equity (TTM)") + td').text.strip()
values['Dividend Yield'] = fundamentals.select_one('th:contains("Dividend Yield") + td').text.strip()
#add values to the sector dictionary
sect[name] = values
# add the dictionary to the list
lst.append(dict(sect))
# for a dictionary using the list
fidelity_sector_report['results'] = lst
except:
return 'Something is wrong with details request'
return fidelity_sector_report
except:
return "Something is horribly wrong"
据我所知,它出色地执行了主要任务,问题出现在将已形成的字典附加到列表的阶段 - 而不是添加新的部分,它会被完全覆盖。我通过print(lst)
在该fidelity_sector_report['results'] = lst
行之后放置来解决这个问题。
我应该更改什么才能按计划形成列表(以及相应的字典)?
您应该移动lst=[]
扇区循环的外部。您的问题出现,因为对于每个扇区,您重置lst
并将当前扇区数据附加到空列表中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句