Overview:
Selenium scraper works perfectly in headless mode. Spawning a virtual display shows no errors via XVFB:
from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
vdisplay.stop()
But when I try to run them together, it errors out with:
[ERROR] SessionNotCreatedException: Message: session not created
from disconnected: Unable to receive message from renderer (Session info: chrome=96.0.4664.0)
Traceback:
Traceback (most recent call last):
File "/var/task/slack_main.py", line 34, in handler
scrape_price(asin_list)
File "/var/task/slack_main.py", line 58, in scrape_price
driver = webdriver.Chrome("/opt/chromedriver",options=options)
File "/var/lang/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/var/lang/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 92, in __init__
RemoteWebDriver.__init__(
File "/var/lang/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 275, in __init__
self.start_session(capabilities, browser_profile)
File "/var/lang/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 365, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/var/lang/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 430, in execute
self.error_handler.check_response(response)
File "/var/lang/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
Configuration:
Below is my complete Selenium and XVFB configuration:
from selenium import webdriver
from selenium_stealth import stealth
from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
options = webdriver.ChromeOptions()
prefs = {"browser.downloads.dir": "//tmp//", "download.default_directory": "//tmp//", "directory_upgrade": True}
options.add_experimental_option("prefs", prefs)
options.binary_location = '/opt/chrome/chrome'
#options.add_argument('--headless') #toggled on and off when running with or without XVFB
options.add_argument('--no-sandbox')
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1280x1696")
options.add_argument("--single-process")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-dev-tools")
options.add_argument("--no-zygote")
options.set_capability('unhandledPromptBehavior', 'ignore')
options.add_argument("download.default_directory=/tmp")
driver = webdriver.Chrome("/opt/chromedriver",options=options)
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win32",
fix_hairline=True,
)
vdisplay.stop()
driver.close()
Why is it not connecting to the display? My guess is it has something to do with the '--headless' toggle?
Versions and Tools:
Selenium version 3.141.0
xvfbwrapper version 0.2.9
Docker is used to compile and push to AWS Lambda, base image used (no changes are made in docker file with or without XVFB)
Edit:
Found a pull request for XVFB configuration in the Github Repo of my base image. Even used the exact same code from the pull request and I still recieve the exact same error. Maybe this has something to do with AWS offboard?
Related
why my script run on local phycharm but when i upload my script on VPS ( host )i get errors ?
my python code
`
import json
import socketio
TOKEN = "my-super-token" #You donation alert token
sio = socketio.Client()
#sio.on('connect')
def on_connect():
sio.emit('add-user', {"token": TOKEN, "type": "alert_widget"})
#sio.on('donation')
def on_message(data):
y = json.loads(data)
print(y['username'])
print(y['message'])
print(y['amount'])
print(y['currency'])
sio.connect('wss://socket.donationalerts.ru:443',transports='websocket')
`
from localhost , pycharmall work but from host i get this
error screenshot here
error :
Traceback (most recent call last): File "test.py", line 22, in
sio.connect('wss://socket.donationalerts.ru:443',transports='websocket')
File "/usr/local/lib/python3.8/site-packages/socketio/client.py", line
338, in connect
raise exceptions.ConnectionError(exc.args[0]) from None socketio.exceptions.ConnectionError: Connection error
i try install ,reinstall python , packages etc
I use that guide to retrieve data from my Fingerbot: https://www.home-assistant.io/integrations/tuya/
I also use that repo to extract the data:
https://github.com/redphx/tuya-local-key-extractor
When I use the extract.py file I get that error:
Exception in thread Thread-1:
Traceback (most recent call last):
openapi <tuya_iot.openapi.TuyaOpenAPI object at 0x7f52fff924c0>
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
openmq <TuyaOpenMQ(Thread-1, started 139994399807232)>
self.run()
File "/home/xavier/.local/lib/python3.8/site-packages/tuya_iot/openmq.py", line 158, in run
self.__run_mqtt()
File "/home/xavier/.local/lib/python3.8/site-packages/tuya_iot/openmq.py", line 164, in __run_mqtt
mq_config = self._get_mqtt_config()
File "/home/xavier/.local/lib/python3.8/site-packages/tuya_iot/openmq.py", line 67, in _get_mqtt_config
"uid": self.api.token_info.uid,
AttributeError: 'NoneType' object has no attribute 'uid'
Traceback (most recent call last):
File "./extract.py", line 41, in <module>
device_manager.update_device_list_in_smart_home()
File "/home/xavier/.local/lib/python3.8/site-packages/tuya_iot/device.py", line 239, in update_device_list_in_smart_home
response = self.api.get(f"/v1.0/users/{self.api.token_info.uid}/devices")
AttributeError: 'NoneType' object has no attribute 'uid'
Here is the code I use:
import json
import logging
import os
from config import (
ENDPOINT,
APP,
EMAIL,
PASSWORD,
ACCESS_ID,
ACCESS_KEY,
)
from tuya_iot import (
TuyaOpenAPI,
AuthType,
TuyaOpenMQ,
TuyaDeviceManager,
)
openapi = TuyaOpenAPI(ENDPOINT, ACCESS_ID, ACCESS_KEY, AuthType.SMART_HOME)
openapi.connect(EMAIL, PASSWORD, country_code=84, schema=APP.value)
openmq = TuyaOpenMQ(openapi)
openmq.start()
print('openapi {}'.format(openapi))
print('openmq {}'.format(openmq))
device_manager = TuyaDeviceManager(openapi, openmq)
device_manager.update_device_list_in_smart_home()
devices = []
for tuya_device in device_manager.device_map.values():
device = {
'device_id': tuya_device.id,
'device_name': tuya_device.name,
'product_id': tuya_device.product_id,
'product_name': tuya_device.product_name,
'category': tuya_device.category,
'uuid': tuya_device.uuid,
'local_key': tuya_device.local_key,
}
try:
resp = openapi.get('/v1.0/iot-03/devices/factory-infos?device_ids={}'.format(tuya_device.id))
factory_info = resp['result'][0]
if 'mac' in factory_info:
mac = ':'.join(factory_info['mac'][i:i + 2] for i in range(0, 12, 2))
device['mac_address'] = mac
except Exception as e:
print(e)
devices.append(device)
print(json.dumps(devices, indent=2))
os._exit(0)
I am on Ubuntu 20.04 and I install the python sdk with tha t command:
pip3 install tuya-iot-py-sdk
I am trying to connect to memsql (running as docker container - cluster-in-a-box). I am using Python3.9. Tried with Python 3.8 as well.
Here is the code snippet:
from memsql.common import database
conn = database.connect(host="127.0.0.1", port=3306, user="root")
print(conn.query("show databases"))
When i run this, I am getting the following error:
Traceback (most recent call last):
File "/Users/ngarg/PycharmProjects/memsqlKafka/startup_try.py", line 3, in <module>
conn = database.connect(host="127.0.0.1", port=3306, user="root")
File "/Users/ngarg/Library/Python/3.9/lib/python/site-packages/memsql/common/database.py", line 19, in connect
return Connection(*args, **kwargs)
File "/Users/ngarg/Library/Python/3.9/lib/python/site-packages/memsql/common/database.py", line 62, in __init__
self.reconnect()
File "/Users/ngarg/Library/Python/3.9/lib/python/site-packages/memsql/common/database.py", line 93, in reconnect
conn = _mysql.connect(**self._db_args)
TypeError: 'db' is an invalid keyword argument for connect()
Try to google this, but didn’t find anything. I am blocked on this step.Any help is appreciated.
When you connect from the latest version of Django to SingleStore DB, you might receive the following error message:
django.db.utils.OperationalError: (2012, 'Error in server handshake')
To connect to SingleStore DB, you will need to configure the auth_plugin in the OPTIONS field.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '{HOST}',
'NAME': '{DBNAME}',
'USER': '{USERNAME}',
'PASSWORD' : '{PASSWORD}',
'PORT': '3306',
'OPTIONS': {
'auth_plugin': 'mysql_native_password'
}
}
}
https://support.singlestore.com/hc/en-us/articles/360057857552-Connecting-Django-to-SingleStore-DB
I am using the docker-py client to create containers on a need basis. So for this, I am using a generator to come up with a port number and trying to use httpd image on a particular port of the host from the generator. But, the client gives out ("invalid port specification: "port number here"") for any number, for any port number that I am trying to use.
Below is sample code that I am trying:
import docker
client = docker.from_env()
container= client.containers.run(image="httpd", ports={'80/tcp': 43545}, detach=True)
To note: The number 43545 does not have any significance here.
Docker details:
Client - 19.03.6
API Version - 1.40
Engine: 19.03.6
Error:
File "/project/api/.venv/lib/python3.7/site-packages/docker/models/containers.py", line 803, in run
detach=detach, **kwargs)
File "/project/api/.venv/lib/python3.7/site-packages/docker/models/containers.py", line 861, in create
resp = self.client.api.create_container(**create_kwargs)
File "/project/api/.venv/lib/python3.7/site-packages/docker/api/container.py", line 429, in create_container
return self.create_container_from_config(config, name)
File "/projectapi/.venv/lib/python3.7/site-packages/docker/api/container.py", line 440, in create_container_from_config
return self._result(res, True)
File "/projectpi/.venv/lib/python3.7/site-packages/docker/api/client.py", line 267, in _result
self._raise_for_status(response)
File "/projectapi/.venv/lib/python3.7/site-packages/docker/api/client.py", line 263, in _raise_for_status
raise create_api_error_from_http_exception(e)
File "/projectyter/api/.venv/lib/python3.7/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 400 Client Error: Bad Request ("invalid port specification: "43545"")
I have working app on the localhost but when I deployed to the AWS it shows several errors.It can receive my sent image but it cant save it. I tried change permissions with chmod,still its not working. This is first time i am deploying flask app,so I dont know much about i My code is as follow:
***modules***
ImageFile.LOAD_TRUNCATED_IMAGES = True
app = flask.Flask(__name__)
#app.route('/', methods = ['GET','POST'])
def hello():
return 'hey there!!!'
#app.route('/imageupload', methods = ['GET','POST'])
def handle_request():
try:
imagefile = flask.request.files['image']
filename = werkzeug.utils.secure_filename(imagefile.filename)
print("\nReceived image file name:" + imagefile.filename)
imagefile.save(filename)
print("hey")
for image in glob.glob('./frames/*.*'):
img_filter(imagefile,image)
json = flask.request.values['Id']
return {"status": "true","message": "Uploaded Successfully", "Id": json }
except:
return {"status" : "false"}
if __name__ == '__main__' :
app.run()
And these are the errors :
Received image file name:1.jpg
ERROR:image_flask:Exception on /imageupload [POST]
Traceback (most recent call last):
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/flask/app.py", line 2446, in ws$
response = self.full_dispatch_request()
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/flask/app.py", line 1951, in fu$
rv = self.handle_user_exception(e)
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/flask/app.py", line 1820, in ha$
reraise(exc_type, exc_value, tb)
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/flask/_compat.py", line 39, in $
raise value
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/flask/app.py", line 1949, in fu$
rv = self.dispatch_request()
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/flask/app.py", line 1935, in di$
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/html/pic-edit/image_flask.py", line 26, in handle_request
imagefile.save(f'/home/ubuntu/pic-edit/{filename}')
File "/home/ubuntu/pic-edit/env/lib/python3.6/site-packages/werkzeug/datastructures.py", li$
dst = open(dst, "wb")
PermissionError: [Errno 13] Permission denied: '/home/ubuntu/pic-edit/1.jpg'
you don't have the right permission. Try to open first the folder with chmod -R 700 /home/ubuntu/pic-edit/
Please note open the permissions like this can be dangerous. Rather I would assign the permission to the "Flask" - Running user
Further for investigations under which user are you running the flask app? How do you start the app?
Also you might change the handle func to:
def handle_request():
try:
f = request.files['file']
f.save(secure_filename(f.filename))
json = flask.request.values['Id']
return {"status": "true","message": "Uploaded Successfully", "Id": json }
note you nead to import from flask import request
I got it where I went wrong, that is because of permissions to the folder. I already tried "chmod 755" to it but it did not worked. After that I tried
chmod a+rwx
And that work fluently.