How can i "reload" my string in a loop python - python

So i have some code pulling a unique id from a webpage, i then use that id in a loop and when its used i want it to get a new unique id, i know i can put the code pulling ids into the loop, but i use the code to tell the loop how long it should run. So is there anyway i can reload the id without putting all the code in the loop?
followrequestsnumber = jsonfollowrequests.count("\",\"username\"")
approveid = jsonfollowrequests[startapproveid:stopapproveid]
while followrequestnumber >=1:
uses the id on this line.
loop ends and now i want to switch the approveid to a new one

Why not something like this?
followrequestsnumber = jsonfollowrequests.count("\",\"username\"")
while followrequestnumber >=1:
approveid = jsonfollowrequests[startapproveid:stopapproveid]
followrequestsnumber = jsonfollowrequests.count("\",\"username\"")
...

Related

Issue with a python string loop

So I'm having trouble getting my code to use a list of strings as inputs in a loop. Here's roughly what I have so far.
from arcgis.gis import GIS
Users = ['User01','User02','User03']
User_string = str(Users) # Have to do this as code needs input as string
gis = GIS("https://www.arcgis.com","USERNAME","PASSWORD") # This logs you into ArcGIS Online
User_role = 'org_user'
for x in User_string:
test = gis.users.get(username=x)
test.update_role(role=User_role)
print("Done! Check Web")
I just can't get the loop to work right. When I remove the for loop and put each user name in individually the get user and update role commands work just fine, it's just in the loop that is broken.
The two errors I'm getting is that the username has to be a string. I fixed that by adding the str() command, but I can't get the username to enter into the user.get loop.
Any suggestions? This code is actually looking at an excel file to produce the list of usernames so I can't just hardcode the list into the code. If it helps at all the website I've been using for the ArcGIS portion of the code is this one: https://developers.arcgis.com/python/guide/accessing-and-managing-users/
I should mention that I also tried just printing
test=gis.users.get(username=User_string)
And it came back as None. So I guess my question is how do I get 'User01' to go into the username=x spot?
Thanks much!
You're doing a for with the list as a string so it's looping on each character of the string. You need to do it with the original list.
Based on your code, you are telling your for loop to iterate on a String, since you converted your list to a string with User_string = str(Users); So the loop is going over each character on the string, which now it is User01User02User03
What you need to do is to iterate the list Users, like:
from arcgis.gis import GIS
Users = ['User01','User02','User03']
gis = GIS("https://www.arcgis.com","USERNAME","PASSWORD") # This logs you into ArcGIS Online
User_role = 'org_user'
for x in Users:
test = gis.users.get(username=x)
test.update_role(role=User_role)
print("Done! Check Web")

Processing all data in a for loop instead of only one element

I wrote some code in order to scrape some data from a website. When I run the code manually I can get all the information for all the shoes, but when I run my script it only gives me one result for each variable.
What can I change to get all the results I want?
For example, when I run the following, I only get one result for marque and one for modele, but when i do it in my terminal I can see that vignette contains multiple values.
import requests
from bs4 import BeautifulSoup
r=requests.get('https://www.sarenza.com/store/product/gender-type/list/view?gender=1&type=76&index=0&count=99')
soup=BeautifulSoup(r.text,'lxml')
vignette=soup.find_all('li',class_='vignette')
for i in range(len(vignette)):
marque=vignette[i].contents[3].text
modele=vignette[i].contents[5].contents[3].text
You're updating your marque and modele variables overwriting their previous value on each iteration of the loop. At the end of the loop, they will only contain the last values that were assigned to them.
If you want to extract all the values, you need to use two lists, and append values to them like this:
marques = []
modeles = []
for i in range(len(vignette)):
marques.append(vignette[i].contents[3].text)
modeles.append(vignette[i].contents[5].contents[3].text)
Or, in a more Pythonic way:
marques = list(v.contents[3].text for v in vignette)
modeles = list(v.contents[5].contents[3].text for v in vignette)
Now you'll have all the values you need, and you can process them or print them out, like this:
for marque, modele in zip(marques, modeles):
print('Marque:', marque, 'Modèle:', modele)

how to stop python loop from stacking information

I plan to automate in python something that will create several .docx files using a while loop. Each file will have its own unique name and have some information inside of it. My problem is that when looping, the information I get inside the documents is stacking.
I believe there is a simple solution out there, I just can't seem to find it.
Here is the block of code:
i=1
while i < 10:
os.chdir("C:\\Users\\user\\Desktop\\" +FolderName)
doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx');
doc.add_paragraph('Title/Keyword:'+str(titles[i]));
doc.add_paragraph('Reasech Link:'+str(link[i]));
doc.add_paragraph('Target Site:'+str(keyword[i]));
doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx');
i+=2
This is the first document. I would like every document to have an output like this
This is the last document created, as you can see the information from the first document as well as the next 3 documents are all stacked and shown in the final output of this last document
Rearrange your code like this:
os.chdir("C:\\Users\\user\\Desktop\\" +FolderName)
i=1
while i < 10:
doc = Document()
doc.add_paragraph('Title/Keyword:'+str(titles[i]));
doc.add_paragraph('Research Link:'+str(link[i]));
doc.add_paragraph('Target Site:'+str(keyword[i]));
doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx');
i+=2

creating list/tuple from string

Sorry if this has been asked,I wasnt able to find it. I am building a slackbot and was looking to be able to loop through inputted data. The user would entered in IDs and the script would loop through those ids and return values. I am able to get it working if a single ID is entered but I was looking to have it search multiple IDs at once.
Entered in slack
#SlackBot search id1,id2,id3
I tried to enter the info from the chat into a list separated by a comma but python treats every character as a new asset in the list. (i,d,1, ,i,d,2,..)
I was able to have the data entered into a dictionary and when printed it shows as
[id1,id2,id3]
So i tried to loop through the dictionary but it treats that string as one object and doesnt loop.
def assetSearch(enteredID):
idList =[enteredID.upper()]
searchedIDs = list()
for eid in idList:
print(eid) # This is here to see what its looking at
for k, v in Content.items():
if v['AssetID'] == eid:
the current print(eid) prints [id1,id2,id3] instead of id1, then id2.
Could someone point me in the correct direction?
You need to do
idList = enteredID.upper().split(",")

Infinite For Loop issue in Python

I need to extract an ID from a JSON string that is needed for loading information into a MySQL database. The ID is a 5 or 6 digit number, but the JSON key that contains this number is the URL net_devices resource string that has the number at the end like this example:
{u'router': u'https://www.somecompany.com/api/v2/routers/123456/'}
Since there is not a key with just the ID, I have used the following to return just the ID from the JSON key string:
url = 'https://www.somecompany.com/api/v2/net_devices/?fields=router,service_type'
r = json.loads(s.get((url), headers=headers).text)
status = r["data"]
for item in status:
type = item['service_type']
router_url = item['router']
router_id = router_url.replace("https://www.somecompany.com/api/v2/routers/", "")
id = router_id.replace("/", "")
print id
This does indeed return just the ID values I want, and it doesn't matter if the result varies in the number of digits.
The problem: This code creates an infinite loop when I include the two lines above the print statement.
How can I change the syntax to allow the loop to run through all the returned IDs once, but still strip out everything except the numerical ID?
I am new to Python, and just starting to write code again after a very long hiatus since college. Any help would be greatly appreciated!
UPDATE
Thanks everyone for the feedback! With the help from David and Gerrat, I was able to find the issue that was causing the infinite loop and it was not this segment of the code, but another segment that was not properly indented. I am learning how to properly indent loops in Python, and this was one of my silly mistakes! Thanks again for the help!

Categories

Resources