I encountered a problem which I do not understand why my code is working this way. Essentially I am attempting to run a for loop for x amount of times but my code keeps saying TimeoutException
Traceback (most recent call last):
File "/Users/Ryan/Desktop/selftest1.py", line 33, in <module>
EC.presence_of_element_located((By.ID, "ctl00_lblStockname"))
File "/Library/Python/2.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
TimeoutException: Message:
And the body of my code is :
for x in range(1,10):
baseurl = 'http://www.hkexnews.hk'
url = 'http://www.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx'
driver = webdriver.Firefox()
driver.get(url)
driver.find_element_by_id("ctl00_txt_stock_code").clear()
driver.find_element_by_id("ctl00_txt_stock_code").send_keys(x)
driver.find_element_by_id("ctl00_rbAfter2006").click()
Select(driver.find_element_by_id("ctl00_sel_DateOfReleaseFrom_y")).select_by_visible_text("1999")
Select(driver.find_element_by_id("ctl00_sel_tier_1")).select_by_visible_text("Financial Statements/ESG Information")
Select(driver.find_element_by_id("ctl00_sel_tier_2")).select_by_visible_text("Annual Report")
driver.find_element_by_css_selector("label > a > img").click()
match = re.compile('\.(html|pdf)')
try:
element = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.ID, "ctl00_lblStockname"))
)
finally:
f = driver.page_source
soup = BeautifulSoup(f,'html.parser')
for link in soup.findAll('a'):
try:
href = link['href']
if re.search(match, href):
file = open("newfile.txt", "a")
file.write(baseurl+href+'\n')
file.close
print ('finished write')
print baseurl+href
except KeyError:
pass
driver.quit()
To my understanding the timeout exception is being thrown because of the first try. But shouldn't the loop stop when it hits finally? Also I attempted to add an exception after 'try' and before 'finally' for timeout error and it gave me the error
error: [Errno 61] Connection refused
I am honestly lost at how to fix this issue or what is causing the issue in the first place.
EDIT:
I added back a exception block after resetting everything and it seems to be working fine now. As in:
try:
...
except TimeoutException:
driver.quit
finally:
...
Just for future references if anyone wants to know the solution.