首页 > 解决方案 > 为什么我的 for 循环会覆盖我以前在字典中的值?(python3)

问题描述

我正在为 msn 钱创建一个刮刀。我从网站上获取值并通过几个 for 循环运行它们以按年份对它们进行排序。当我的 for 循环完成时,所有值都是 2018 年数据集中的值。我的代码有什么问题?

from urllib.request import urlopen
from bs4 import BeautifulSoup
from lxml import etree

values = {}
values_by_year = {}
counter = 2013
dict_index = 0
temp = ''

url = "https://www.msn.com/en-us/money/stockdetails/financials/nas-googl/fi-a1u3rw?symbol=GOOGL&form=PRFIHQ"
tree = etree.HTML(urlopen(url).read())

for section in tree.xpath('//*[@id="table-content-area"]'):
    for i in range(2, 32):
        for x in     section.xpath('./div/div/div[1]/div/ul[%s]/li[1]/p/text()'
% (i)):
                if i == 6:
                    values[i] = 0
                else:
                    values[x] = 0

for x in range(2015, 2019):
    values_by_year[x] = values


for section in tree.xpath('//*[@id="table-content-area"]'):
    for i in range(2, 32):
        for y in range(1, 6):
            for value in section.xpath(
                    './div/div/div[1]/div/ul[%s]/li[%s]/p/text()' %     (i,y)):

                if y == 1:
                    temp = value
                else:
                    print("value is ", counter+y, "y is ", y)
                    values_by_year[counter+y][temp] = value



print(values_by_year[2016])
print("\n------\n")
print(values_by_year[2017])

我没有收到任何错误消息。我的预期结果是程序输出一个字典名称 values_by_year ,其中包含每年的 4 个键。每一年都包含对应于年份的值的字典。例如,2015 年的“期间结束日期”为 2015 年 12 月 31 日,2016 年为 2016 年 12 月 31 日。

标签: pythonpython-3.xbeautifulsouplxmlurllib

解决方案


我不确定你是否在此之后。但是使用Beautifulsoup你可以做到这一点。

from bs4 import BeautifulSoup
import requests
import re
headers={'User-Agent':'Mozilla/5.0'}
data=requests.get('https://www.msn.com/en-us/money/stockdetails/financials/nas-googl/fi-a1u3rw?symbol=GOOGL&form=PRFIHQ',headers=headers).text
soup=BeautifulSoup(data,'html.parser')
dict_data={}
table=soup.select_one('div.table-rows')
cols=table.select('.column-heading .truncated-string')
for col in cols[1:]:
    year=col.text
    periodenddate=col.parent.find_next('div',class_='table-data-rows').find('p',title=re.compile(year)).text
    dict_data[year]=periodenddate

print(dict_data)

在控制台上打印的输出:

{'2015': '12/31/2015', '2018': '12/31/2018', '2016': '12/31/2016', '2017': '12/31/2017'}

推荐阅读