Incorrect iteration

Clash Royale CLAN TAG#URR8PPPIncorrect iteration
I'm cycling through several URLs. For each URL, I want to check to see if the webname has the name of an animal in the URL string. If so, store "Animal Website" in excel row. If not, store "Regular Website" in excel row.
Currently, I am not getting the results I as expected. I am getting all Regular Website stored in each row of excel, even though the first iteration has an animal name.
Here are the websites (they are fake - only for illustration purposes):
www.cats.com
www.plants.com
www.cars.com
www.planes.com
The first iteration has an animal's name, therefore I should get that name stored in excel sheet, row 1. The second, third, and forth iteration does not have an animal and thus those names should be stored on excel sheet, row 2, 3, and 4.
import openpyxl
wb = openpyxl.load_workbook('/path/filename.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
for url in urls:
website_name = url
animals = ['cat', 'dog', 'bird']
for animal in animals:
if animal in website_name:
print('this website has an animal')
name = 'Animal Website'
sheet['I' + str(row)].value = name
else:
print('this record has NO an animal')
name = 'Regular Website'
sheet['I' + str(row)].value = name
wb.save('/path/filename.xlsx')
How can I rewrite the code for it to work correctly?
for
website_name
for animal
1 Answer
1
Your current code will set the website name as the last URL in your list.
Try something like this:
for url in urls:
for animal in animals:
if animal in url:
# do stuff
This will loop through each URL and check if each animal name is contained.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This is not a question about excel or openpyxl, because you have no problem writing into the xlsx file. This is a question about your coding logic. Also, it seems your "pseudo code" is valid python, and you should label it as such. If it's pseudo-code, you'll be requested to provide a Minimal, Complete, and Verifiable example, and you'll likely find your problem as your write it. Here's a big hint to your problem: the code you wrote implies you want a nested
forloop - for each url, see if it's an animal. The code you provided has no such nesting. Try printingwebsite_namein yourfor animalloop.– Scott Mermelstein
24 mins ago