I'm still new to Python and I wrote some code to help me go through some online listings.
I had to get some error handling in there as when an attribute of the listing isn't found, it would crash the program.
If I try to use pass or continue I just get stuck in an infinite loop, as expected.
I feel like I've written myself into a corner and I just can't seem to find a solution. The solutions I found I could not figure out and most were for other languages.
How can I make this work so that the loop doesn't skip over all of the other attributes once an error is found?
EDIT: I think my post was unclear on that point, my apologies. What happens is this: If the element of interest in a listing is not found, the other elements are skipped over. So if the listing has no owner name specified (the first element or attribute), the whole listing gets ignored. It continues on to the next listing. Any idea how I could fix that?
Here's the part of the code:
#iterate through the results according to user input earlier
i = 0
while (i < number_of_results):
Result_page = driver.current_url
#define elements of the listing of interest
stran = requests.get(driver.current_url)
soup = BeautifulSoup(stran.content, 'html.parser')
ime = soup.find("dd", itemprop="name")
ulica = soup.find("dd", itemprop="streetAddress")
postna_stevilka = soup.find("span", itemprop="postalCode")
kraj = soup.find("span", itemprop="addressLocality")
tel = soup.find("dd", itemprop="telephone")
spletna_stran = soup.find("dd", itemprop="url")
mobil = soup.find("a", itemprop="telephone")
try:
print(ime.text)
c1 = sheet.cell(row=i+1, column=1)
c1.value = ime.text
print(ulica.text)
c1 = sheet.cell(row=i+1, column=2)
c1.value = ulica.text
print(postna_stevilka.text)
c1 = sheet.cell(row=i+1, column=3)
c1.value = postna_stevilka.text
print(kraj.text)
c1 = sheet.cell(row=i+1, column=4)
c1.value = kraj.text
print(tel.text)
c1 = sheet.cell(row=i+1, column=5)
c1.value = tel.text
#print(mobil.text) does not work, cut out to prevent error
print(spletna_stran.text)
c1 = sheet.cell(row=i+1, column=6)
c1.value = spletna_stran.text
#catch the error when an entry isn't there
except AttributeError:
print("No such entry.")
next_entry = driver.find_element_by_xpath("/html/body/main/chousingdetail/div/div[2]/div[1]/nav/div/div[2]/a[2]/i")
next_entry.click()
i +=1