So what i am trying to do is create a function that sets and starts my headless browser with a new proxy. And then call that function and go to a website. Sometimes I get a connection error, and while I have figured out how to re-try, that connection error will not be solved unless i have restarted the browser. Hence, why i was looking to create a setbrowser() function to call in the Exception case, which will restart the browser with a new proxy and TRY AGAIN to pull the URL.
See code below:
#!/usr/bin/env python2.7
import datetime
from selenium import webdriver
#import sys
from pyvirtualdisplay import Display
#import csv
from selenium.common.exceptions import NoSuchElementException
import time
import requests
def startbrowser():
browser = None
display = None
display = Display(visible=0, size=(800, 600))
### using proxicity to get the proxy values ###
for attempt in range(1,20):
try:
API = "value"
url = "https://www.proxicity.io/api/v1/{}/proxy?isAnonymous=true&country=US".format(API)
url_proxicity = "https://www.proxicity.io"
p = requests.get(url_proxicity)
if p.status_code == 200:
r = requests.get(url).json()
proxy_ip = r["ip"]
proxy_port = r["port"]
print(proxy_ip)
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", proxy_ip)
profile.set_preference("network.proxy.http_port", proxy_port)
profile.update_preferences()
display.start()
browser = webdriver.Firefox(firefox_profile=profile)
break
else:
display.start()
browser = webdriver.Firefox()
print("browser is set")
break
except Exception as e:
print(e," Attempt:" + str(attempt))
time.sleep(10)
pass
### Proxicity Complete ###
return display
return browser
startbrowser()
try:
for i in range(1,3):
url = "http://www.google.com"
for attempt in range(1,5):
try:
browser.get(url)
print("browser success",i)
break
except Exception as e:
print(e," Attempt:" + str(attempt))
time.sleep(8)
startbrowser()
pass
finally:
if browser is not None:
browser.quit()
if display is not None:
display.stop()
[edit by admin: formatting]