簡體   English   中英

For 循環只返回最后一個值 python

[英]For loop returns only the last Value python

我對python很陌生。 我正在嘗試抓取搜索欄,但是當我在循環中傳遞數組時,它只返回最后一個值輸出。 這是我正在使用的代碼

searches=['888888','600606','100666']

for search in searches: 
      url="https://www.safaricom.co.ke/get-more/smart-tools/m-pesa-tools"
      wd.get(url)
      wd.implicitly_wait(30)
      search_field=wd.find_element_by_id("search")
      search_field.send_keys(search)
      searchButton=wd.find_element_by_id("get_paybill")
      searchButton.click()
      table=wd.find_elements_by_id("paybill_div_result")

我得到的輸出只是最后一個值“100666”

df=pd.read_html(wd.page_source)
df=df[2]
df=pd.DataFrame(df)
df
Name    Paybill
0   Wakenya Pamoja Paybill: 100666
1   Wakenya Pamoja Paybill: 100666

我試過附加表格,但它拋出以下錯誤。

StaleElementReferenceException Traceback(最近一次調用最后一次)

您需要將獲得的值存儲在某處。 否則,它將一遍又一遍地覆蓋table值,並且只返回最后一個值。

例如,您可以在循環之前創建一個空列表lst ,並且每當table重新運行一個值時,將其附加到lst 最后,您將擁有一個表/數據框對象列表。

lst = [] # Create a list to store the values
for search in searches: 
      url="https://www.safaricom.co.ke/get-more/smart-tools/m-pesa-tools"
      wd.get(url)
      wd.implicitly_wait(30)
      search_field=wd.find_element_by_id("search")
      search_field.send_keys(search)
      searchButton=wd.find_element_by_id("get_paybill")
      searchButton.click()
      table=wd.find_elements_by_id("paybill_div_result")
      lst.appned(table) # Append values to you list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM