Python newbie here,
I am trying to create a code that would search a name from a website and store it in a text file. If the code detects the same name in the text file it will add a certain number to käytymäärä (käytymäärä = käytymäärä + end) (käyty_määrä is a counter of how many times it has found the element and clicked it). That is because I want to skip the names that I have searched earlier.
käyty_määrä = 1
def klikkaa_nimeä():
while True:
try:
#code with possible error
ihmiset = driver.find_element_by_xpath("/html/body/div[3]/main/div[3]/div/div/div/section/table/tbody/tr[{}]/td[1]/a".format(käyty_määrä))
except:
#Press button if it cant find element
nappi = driver.find_element_by_xpath("/html/body/div[3]/main/div[3]/div/div/div/section/a")
nappi.click() #THE CODE GETS STUCK HERE IF EDIT THE VARIABLE DOWN THERE
else:
#Rest of the code
ActionChains(driver).key_down(Keys.CONTROL).click(ihmiset).key_up(Keys.CONTROL).perform() #Opens a window in a newtab
driver.switch_to.window(driver.window_handles[1]) #Vaihtaa keskittymisen uuteen tabiin
#Tries to find a numbers
try:
numbers = driver.find_element_by_xpath('/html/body/div[3]/main/div[3]/div/div/div/section/div[1]/div[1]/table/tbody/tr[1]/td[2]/a').text
except:
driver.close()
break
else:
#Checks that it is a numbers not a name.
first_chars = numbers[0:3]
numeroita = str(first_chars)
if numeroita.isdigit() is True:
with open("osoitteet.txt", "r+") as osoitteet:
Tiedetyt_yritykset = set(name.strip() for name in osoitteet)
if driver.current_url in Tiedetyt_yritykset:
print("Yritys on katsottu läpi")
with open("paljonko.txt") as määrä:
määrä.write("\n")
määrä.write(str(käyty_määrä))
lines = määrä.readlines()
end = lines[-1].split(',')[0]
end = int(end)
käyty_määrä = käyty_määrä + end #THIS PART MAKES THE CODE ACT DIFFERNTLY IT MAKES IT STUCK IN A LOOP. If I remove the whole variable from here it works fine. Why does it make a difference?
break
#Wrong kind of name
else:
print("Test")
käyty_määrä = käyty_määrä + 1
This is inside of my loop and if I edit the variable käyty_määrä. I will add a number from a text file it won't work and will just get stuck in a loop. Why does it do that?
More info:
Text file:
It will add the amount of how many times it has visited the website.
I hope that my explanation is not very confusing. Please ask if this makes you confused. (:
I have two guesses what could cause it.
- It won't recognize the variable (käyty_määrä) as a number and because of that it won't find the element.
- A Newline in the text file is preventing the element to be not found.