简体   繁体   English

For 循环只返回最后一个值 python

[英]For loop returns only the last Value python

I'm quite new in python.我对python很陌生。 I'm trying to scrape a search bar but when I pass the array on the loop it only returns the last value output.我正在尝试抓取搜索栏,但是当我在循环中传递数组时,它只返回最后一个值输出。 Here is the code I'm using这是我正在使用的代码

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")

the output I get is only of the Last value "100666"我得到的输出只是最后一个值“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

I have tried appending the table but it's throwing the below error.我试过附加表格,但它抛出以下错误。

StaleElementReferenceException Traceback (most recent call last) StaleElementReferenceException Traceback(最近一次调用最后一次)

you need to store the values you get somewhere.您需要将获得的值存储在某处。 Otherwise, it will override the table value over and over again and will return the last one only.否则,它将一遍又一遍地覆盖table值,并且只返回最后一个值。

For instance, you can create an empty list lst before the loop and whenever table reruns a value append it to lst .例如,您可以在循环之前创建一个空列表lst ,并且每当table重新运行一个值时,将其附加到lst In the end, you'll have a list of table/dataframe objects.最后,您将拥有一个表/数据框对象列表。

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