I'm trying use pywinauto to start browser, Chrome or FireFox. But I can`t find the name of application:
from pywinauto.application import Application
if self.browser == "chrome":
app = Application(backend="uia").start ("C:\Program Files\Google\Chrome\Application\chrome.exe --force-renderer-accessibility")
time.sleep(10)
app["Кто использует Chrome?"].print_control_identifiers()
I use inspcet.exe to get elements name:
inspect.exe data:
Name: "Кто использует Chrome?" (cyrylic/russian name)
ControlType: UIA_PaneControlTypeId (0xC371)
LocalizedControlType: "панель"
BoundingRectangle: {l:388 t:141 r:1428 b:938}
IsEnabled: true
ProcessId: 61944
RuntimeId: [2A.3206BA]
FrameworkId: "Win32"
ClassName: "Chrome_WidgetWin_1"
...
The window is open normally - it's the Chrome pane for chooosing user-profile.
But error:
Traceback (most recent call last):
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 258, in __resolve_control
criteria)
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/shulya403/Shulya403_works/all_gid_2/Scraper/ya_scrape_experiment1.py", line 346, in <module>
CromeWindwow = WinChrome(browser="chrome")
File "C:/Users/shulya403/Shulya403_works/all_gid_2/Scraper/ya_scrape_experiment1.py", line 333, in __init__
app[r"Кто использует Chrome?"].print_control_identifiers()
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 613, in print_control_identifiers
this_ctrl = self.__resolve_control(self.criteria)[-1]
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 261, in __resolve_control
raise e.original_exception
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\application.py", line 203, in __get_ctrl
dialog = self.backend.generic_wrapper_class(findwindows.find_element(**criteria[0]))
File "C:\Users\shulya403\Shulya403_works\all_gid_2\venv\lib\site-packages\pywinauto\findwindows.py", line 87, in find_element
raise ElementNotFoundError(kwargs)
pywinauto.findwindows.ElementNotFoundError: {'best_match': 'Кто использует Chrome?', 'backend': 'uia', 'process': 65412}
One time it has no timeout, and it show English alternative of names [u'Кто использует Chrome?', 'Pane', '...']
variant:
app.Pane.print_control_identifiers()
worked one time only. But next run returned to the error.
I try with FireFox window too, with same result.
Related
I have followed the tutorial from readthedocs: https://channels.readthedocs.io/en/stable/tutorial/index.html
for django channels. Everything worked fine until the last part of the tutorial, about testing.
Here is the test file as well as the traceback.
# chat/tests.py
from channels.testing import ChannelsLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
class ChatTests(ChannelsLiveServerTestCase):
serve_static = True # emulate StaticLiveServerTestCase
#classmethod
def setUpClass(cls):
super().setUpClass()
try:
# NOTE: Requires "chromedriver" binary to be installed in $PATH
cls.driver = webdriver.Chrome()
except:
super().tearDownClass()
raise
#classmethod
def tearDownClass(cls):
cls.driver.quit()
super().tearDownClass()
def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self):
try:
self._enter_chat_room('room_1')
self._open_new_window()
self._enter_chat_room('room_1')
self._switch_to_window(0)
self._post_message('hello')
WebDriverWait(self.driver, 2).until(lambda _:
'hello' in self._chat_log_value,
'Message was not received by window 1 from window 1')
self._switch_to_window(1)
WebDriverWait(self.driver, 2).until(lambda _:
'hello' in self._chat_log_value,
'Message was not received by window 2 from window 1')
finally:
self._close_all_new_windows()
def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self):
try:
self._enter_chat_room('room_1')
self._open_new_window()
self._enter_chat_room('room_2')
self._switch_to_window(0)
self._post_message('hello')
WebDriverWait(self.driver, 2).until(lambda _:
'hello' in self._chat_log_value,
'Message was not received by window 1 from window 1')
self._switch_to_window(1)
self._post_message('world')
WebDriverWait(self.driver, 2).until(lambda _:
'world' in self._chat_log_value,
'Message was not received by window 2 from window 2')
self.assertTrue('hello' not in self._chat_log_value,
'Message was improperly received by window 2 from window 1')
finally:
self._close_all_new_windows()
# === Utility ===
def _enter_chat_room(self, room_name):
self.driver.get(self.live_server_url + '/chat/')
ActionChains(self.driver).send_keys(room_name + '\n').perform()
WebDriverWait(self.driver, 2).until(lambda _:
room_name in self.driver.current_url)
def _open_new_window(self):
self.driver.execute_script('window.open("about:blank", "_blank");')
self.driver.switch_to_window(self.driver.window_handles[-1])
def _close_all_new_windows(self):
while len(self.driver.window_handles) > 1:
self.driver.switch_to_window(self.driver.window_handles[-1])
self.driver.execute_script('window.close();')
if len(self.driver.window_handles) == 1:
self.driver.switch_to_window(self.driver.window_handles[0])
def _switch_to_window(self, window_index):
self.driver.switch_to_window(self.driver.window_handles[window_index])
def _post_message(self, message):
ActionChains(self.driver).send_keys(message + '\n').perform()
#property
def _chat_log_value(self):
return self.driver.find_element_by_css_selector('#chat-log').get_property('value')
PS C:\Users\regis\PycharmProjects\mysite> py manage.py test chat.tests
Found 2 test(s).
Creating test database for alias 'default'...
Destroying old test database for alias 'default'...
System check identified no issues (0 silenced).
DevTools listening on ws://127.0.0.1:8872/devtools/browser/6bb10b6b-1101-4147-8f75-bc0b54800912
EETraceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 107, in spawn_main
new_handle = reduction.duplicate(pipe_handle,
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 79, in duplicate
return _winapi.DuplicateHandle(
OSError: [WinError 6] The handle is invalid
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 109, in spawn_main
fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY)
OSError: [Errno 9] Bad file descriptor
======================================================================
ERROR: test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room (chat.tests.ChatTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\django\test\testcases.py", line 266, in _setup_and_call
self._pre_setup()
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup
self._server_process.start()
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'convert_exception_to_response.<locals>.inner'
======================================================================
ERROR: test_when_chat_message_posted_then_seen_by_everyone_in_same_room (chat.tests.ChatTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\django\test\testcases.py", line 266, in _setup_and_call
self._pre_setup()
File "C:\Users\regis\PycharmProjects\mysite\env\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup
self._server_process.start()
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\regis\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'convert_exception_to_response.<locals>.inner'
----------------------------------------------------------------------
Ran 0 tests in 3.753s
FAILED (errors=2)
Destroying test database for alias 'default'...
I am newbie to channels. So far I have only focused on the first error message for the spawn.py file on line 107 but I didn't find out much. Some posts are mentioning forking with multiprocessing not working on Windows but I have no idea what it means.
Thanks for help
It's my first time using MongoDB but I can't seem to fix this one issue, my friend who uses MongoDB doesn't know how to use python so he can't really help me.
Here's my code:
import pymongo
# Replace the uri string with your MongoDB deployment's connection string.
conn_str = "mongodb+srv://sqdnoises:{mypass}#sqd.d4kjb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
# set a 5-second connection timeout
client = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000)
try:
print(client.server_info())
print('\n\n\n aka connected')
except Exception:
print("Unable to connect to the server.")
Where {mypass} is my MongoDB password.
I keep getting this error:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 782, in read_resolv_conf
f = stack.enter_context(open(f))
FileNotFoundError: [Errno 2] No such file or directory: '/etc/resolv.conf'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 88, in _resolve_uri
results = _resolve('_' + self.__srv + '._tcp.' + self.__fqdn,
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 41, in _resolve
return resolver.resolve(*args, **kwargs)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 1305, in resolve
return get_default_resolver().resolve(qname, rdtype, rdclass, tcp, source,
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 1278, in get_default_resolver
reset_default_resolver()
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 1290, in reset_default_resolver
default_resolver = Resolver()
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 734, in __init__
self.read_resolv_conf(filename)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/dns/resolver.py", line 785, in read_resolv_conf
raise NoResolverConfiguration
dns.resolver.NoResolverConfiguration: Resolver configuration could not be read or specified no nameservers.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/storage/emulated/0/! workspace/mongolearn/main.py", line 7, in <module>
client = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/mongo_client.py", line 677, in __init__
res = uri_parser.parse_uri(
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/uri_parser.py", line 532, in parse_uri
nodes = dns_resolver.get_hosts()
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 119, in get_hosts
_, nodes = self._get_srv_response_and_hosts(True)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 99, in _get_srv_response_and_hosts
results = self._resolve_uri(encapsulate_errors)
File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 95, in _resolve_uri
raise ConfigurationError(str(exc))
pymongo.errors.ConfigurationError: Resolver configuration could not be read or specified no nameservers.
How do I fix this?
I am following https://docs.mongodb.com/drivers/pymongo/
indeed, the problem is that dnspython tries to open /etc/resolv.conf
import dns.resolver
dns.resolver.default_resolver=dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers=['8.8.8.8']
Just adde this code to the top of your main code, and that should be sufficient to get you past this hurdle..
I am working Celery with Mongodb( as backend and as a broker).
I follow this tutorial on how to set them up: https://skillachie.com/2013/06/15/intro-celery-and-mongodb/
When I have the security enable on the /etc/mongod.conf file like this:
security:
authorization: enabled
and I call the .get() to get the results of the tasks that I have set up I get this error:
Traceback (most recent call last):
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/kombu/utils/__init__.py", line 323, in __get__
return obj.__dict__[self.__name__]
KeyError: 'collection'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/celery/result.py", line 169, in get
no_ack=no_ack,
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/celery/backends/base.py", line 229, in wait_for
meta = self.get_task_meta(task_id)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/celery/backends/base.py", line 307, in get_task_meta
meta = self._get_task_meta_for(task_id)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/celery/backends/mongodb.py", line 158, in _get_task_meta_for
obj = self.collection.find_one({'_id': task_id})
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/kombu/utils/__init__.py", line 325, in __get__
value = obj.__dict__[self.__name__] = self.__get(obj)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/celery/backends/mongodb.py", line 246, in collection
collection.ensure_index('date_done', background='true')
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/pymongo/collection.py", line 2028, in ensure_index
self.__create_index(keys, kwargs, session=None)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/pymongo/collection.py", line 1894, in __create_index
session=session)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/pymongo/collection.py", line 250, in _command
user_fields=user_fields)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/pymongo/pool.py", line 613, in command
user_fields=user_fields)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/pymongo/network.py", line 167, in command
parse_write_concern_error=parse_write_concern_error)
File "/home/celeryProject/celeryProject/lib/python3.6/site-packages/pymongo/helpers.py", line 159, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: command createIndexes requires authentication
But when I disable the security it is working!
I also tried to change the roles on the user on mongodb and nothing happened.
Also, I have tried to log in with that way:
BROKER_URL = 'mongodb://tester:123456#178.128.250.181:27017/test?authSource=admin'
celery = Celery('EOD_TASKS',broker=BROKER_URL)
Is this a security problem or I can ignore it and move on?
if i'm not mistaken, using authorization: enabled means you need to setup a user/pass to login in order to query the mongodb. by default it is left wide open, which is a security consideration
I am using docker SDK for python and trying to create a container. Following is the code I am executing:
import docker
client = docker.DockerClient(base_url='tcp://10.41.70.76:2375')
image = client.images.get('siab_user_one')
container = client.containers.run(image.tags[0], detach=True)
container.exec_run("ls")
But, the above code throws the following error:
Traceback (most recent call last):
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/client.py", line 261, in _raise_for_status
response.raise_for_status()
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 409 Client Error: Conflict for url: http://10.41.70.76:2375/v1.35/containers/ccdb556fb234eeb86b19d37c30e9d64e428bf42a8d2b70784225dcf3c5347859/exec
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "dock.py", line 7, in <module>
container.exec_run("ls")
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/models/containers.py", line 196, in exec_run
workdir=workdir,
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/utils/decorators.py", line 19, in wrapped
return f(self, resource_id, *args, **kwargs)
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/exec_api.py", line 80, in exec_create
return self._result(res, True)
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/client.py", line 267, in _result
self._raise_for_status(response)
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/api/client.py", line 263, in _raise_for_status
raise create_api_error_from_http_exception(e)
File "/Users/aditya/workspace/term/lib/python3.6/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 409 Client Error: Conflict ("Container ccdb556fb234eeb86b19d37c30e9d64e428bf42a8d2b70784225dcf3c5347859 is not running")
Even after running the container in detached mode, container exits soon after creation.
PS: The docker image is present locally and was created manually.
It works fine with remote images.
I think you need to supply a command to prevent the container from exiting, try this:
container = client.containers.run(image.tags[0], command=["tail", "-f", "/dev/null"],detach=True)
or using tty=True with detach=True will help also
I'm trying to get all results from a predefined google search, but I'm stuck at the following error:
Traceback (most recent call last):
File "C:\python36\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
File "C:\python36\lib\subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "C:\python36\lib\subprocess.py", line 992, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\amzar\Desktop\pyscripts\selen.py", line 23, in <module>
get_results("dog")
File "C:\Users\amzar\Desktop\pyscripts\selen.py", line 6, in get_results
browser = webdriver.Firefox()
File "C:\python36\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 142, in __init__
self.service.start()
File "C:\python36\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
I checked for 30 minutes all possibilities with importing, but I can't figured it out.
from selenium import webdriver
def get_results(search_term):
url = "http://startpage.com"
browser = webdriver.Firefox()
browser.get(url)
search_box = browser.find_element_by_id("query")
search_box.send_keys(search_term)
search_box.submit()
try:
links = browser.find_elements_by_xpath("/ol[#class='web_regular_results']//h3//a")
except:
links = browser.find_elements_by_xpath("//h3//a")
results = []
for link in links:
href = link.get_attribute("href")
printf(href)
results.append(href)
browser.close()
return results
get_results("dog")