Estoy usando selenio para hacer un raspado sin cabeza de un sitio web dentro de un punto final de una API usando Flask para Python. Hice varias pruebas y mi código de extracción de selenio funciona perfectamente dentro de un script y mientras se ejecuta como una API en el host local. Sin embargo, cuando implemento el código en un servidor remoto, las solicitudes siempre devuelven un error 502 Bad Gateway . Es extraño porque al iniciar sesión puedo ver que el raspado está funcionando correctamente, pero el servidor responde con 502 antes de que el raspado termine de procesarse, como si estuviera tratando de configurar un proxy y falla. También noté que al eliminar time.sleep en mi código, devuelve un 200, aunque el resultado podría ser incorrecto porque no le da a Selenium el tiempo adecuado para cargar toda la página para raspar.
También traté de configurar para usar falcon en lugar de matraz y obtengo un error similar. Esta es una muestra de mi código reciente usando Falcon :
class GetUrl(object): def on_get(self, req, resp): """ Get Request :param req: :param resp: :return: """ # read parameter req_body = req.bounded_stream.read() json_data = json.loads(req_body.decode('utf8')) url = json_data.get("url") # get the url options = Options() options.add_argument("--headless") driver = webdriver.Firefox(firefox_options=options) driver.get(url) time.sleep(5) result = False # check for outbound links content = driver.find_elements_by_xpath("//a[@class='_52c6']") if len(content) > 0: href = content[0].get_attribute("href") result = True driver.quit() # make the return return_doc = {"result": result} resp.body = json.dumps(return_doc, sort_keys=True, indent=2) resp.content_type = 'text/string' resp.append_header('Access-Control-Allow-Origin', "*") resp.status = falcon.HTTP_200 Vi otros problemas similares como este , pero aunque puedo ver que hay un gunicorn ejecutándose en mi servidor, no tengo nginx, o al menos no se ejecuta donde debería ejecutarse. Y no creo que Falcon lo use. Entonces, ¿qué estoy haciendo exactamente mal? Un poco de luz en este tema es muy apreciada, ¡gracias!
Esto podría funcionar:
from IPython.display import clear_output import time as time import json !apt-get update !apt install chromium-chromedriver !which chromedriver !pip install selenium import selenium from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.expected_conditions import presence_of_element_located !pip install page_objects import page_objects from page_objects import PageObject, PageElement time.sleep(1) clear_output() class GetUrl(object): def on_get(self, req, resp): """ Get Request :param req: :param resp: :return: """ # read parameter req_body = req.bounded_stream.read() json_data = json.loads(req_body.decode('utf8')) url = json_data.get("https://stackoverflow.com/questions/69038958/selenium-flask-falcon-in-python-502-bad-gateway-error/69546175#69546175") # get the url options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome('chromedriver',options = options) driver.implicitly_wait(3) driver.get("https://stackoverflow.com/questions/69038958/selenium-flask-falcon-in-python-502-bad-gateway-error/69546175#69546175") result = False # check for outbound links contentStorage = [] content = driver.find_elements_by_tag_name('a') for i in content: contentStorage.append(i.get_attribute('text')) result = True #driver.quit() # make the return return_doc = {"result": result} resp.body = json.dumps(return_doc, sort_keys=True, indent=2) resp.content_type = 'text/string' resp.append_header('Access-Control-Allow-Origin', "*") resp.status = falcon.HTTP_200Sin embargo, lo estaba probando sin usar un objeto de clase, y también usa Chrome en lugar de FireFox:
from IPython.display import clear_output import time as time !apt-get update !apt install chromium-chromedriver !which chromedriver !pip install selenium import selenium from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.expected_conditions import presence_of_element_located !pip install page_objects import page_objects from page_objects import PageObject, PageElement time.sleep(1) clear_output() options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome('chromedriver',options = options) driver.implicitly_wait(3) driver.get('https://stackoverflow.com/questions/69038958/selenium-flask-falcon-in-python-502-bad-gateway-error/69546175#69546175') content = driver.find_elements_by_tag_name('a') contentStorage = [] for i in content: contentStorage.append(i.get_attribute('text')) #driver.quit()