对for循环中的特定索引进行计算

时间:2018-12-04 08:03:46

标签: python python-3.x

我尝试编写一个小程序以简化工作,但是我无法理解最后一个基本部分。我对python相当陌生,我很高兴我走了这么远。

该代码遍历6页并从表中提取信息并将其提供。

我现在需要做的是计算第4个输出值的1%,也就是回路索引3(564,09 * 1.01)-其余的应该不计算就排除掉。我认为我在最后一个if else循环中需要一个for语句,但是我无法使它起作用:(

我的代码如下:

# Import libraries
import requests
from bs4 import BeautifulSoup

metalle = ['Ag_processed','Al_cables','Au_processed','DEL_low','MB_MS_63_wire','Pb_Cable']
urls = []
for i in metalle:
    url = 'http://somepage.com/yada.php?action=show_table&field=' + str(i)
    urls.append(url)

for y in urls:
    page = requests.get(y)
    soup = BeautifulSoup(page.text, 'html.parser')

# Remove links
    last_links = soup.find(class_='linkbar')
    last_links.decompose()
    years = soup.find(class_='year')
    years.decompose()

# Pull all text from the section div
    tabelle = soup.find(class_='section')

# Pull text from all instances of <tr> tag within section div, ignore first one, header 1:
    preise = tabelle.find_all('tr')[1:]

# Create for loop to print out all prices
    wert = []
    for tabelle in preise:
    #I FIGURE HERE IS A IF ELSE NEEDED
        preis = tabelle.contents[1]
        wert.append(preis.string)
    print(wert[0])

OUTPUT: 
474,60  
213,06  
38.550,00 
564,09 #THIS NEEDS TO BE CALCULATED +1%
557,00
199,55

我希望您可以帮助Python新手<3

Sandrigo问候

3 个答案:

答案 0 :(得分:0)

您可以使用方法preise将列表enumerate()转换为枚举类型。这意味着,如果您的列表看起来像这样["a", "b", "c"],则可以将其转换为[(0, "a"), (1, "b"), (2, "c"]。因此,您的代码必须如下所示:

for i, tabelle in enumerate(preise):
    if i == 3:
       preis = tabelle.contents[1]*1.01
    else:
       preis = tabelle.contents[1]
    wert.append(preis.string)

答案 1 :(得分:0)

您可以在代码末尾

# format currency to valid number, from 38.550,00 to 38550.00 
wert[3] = wert[3].replace('.', '').replace(',', '.') 
wert[3] = float(wert[3]) * 1.01
print(wert)

答案 2 :(得分:0)

好的,谢谢大家的帮助,我知道了:

工作解决方案:

for (i, y) in enumerate(urls):
    page = requests.get(y)
    soup = BeautifulSoup(page.text, 'html.parser')
    last_links = soup.find(class_='linkbar')
    last_links.decompose()
    years = soup.find(class_='year')
    years.decompose()
    tabelle = soup.find(class_='section')
    preise = tabelle.find_all('tr')[1:]
    wert = []
    for tabelle in preise:
        if i == 3:
            preis = tabelle.contents[1]
            wert.append(preis.string)
            wert[0] = str(wert[0]).replace('.', '').replace(',', '.') 
            wert[0] = float(wert[0]) * 1.01
            wert[0] = str(wert[0]).replace('.', ',')
            break
        else:
            preis = tabelle.contents[1]
            wert.append(preis.string)   
    print(wert[0])

    file.write(str(wert[0]))
    file.write("\n")
file.close()

谢谢大家!