import win32com
import win32com.client
import win32gui
import win32con
import pythoncom
def getIEServer(hwnd, ieServer):
if win32gui.GetClassName(hwnd) == 'Internet Explorer_Server':
ieServer.append(hwnd)
if __name__ == '__main__':
#pythoncom.CoInitializeEx(0) # not use this for multithreading
mainHwnd = win32gui.FindWindow('windowclass', 'windowtitle')
if mainHwnd:
ieServers = []
win32gui.EnumChildWindows(mainHwnd, getIEServer, ieServers)
if len(ieServers) > 0:
ieServer = ieServers[0]
msg = win32gui.RegisterWindowMessage('WM_HTML_GETOBJECT')
ret, result = win32gui.SendMessageTimeout(ieServer, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0)
doc = win32com.client.dynamic.Dispatch(ob)
print doc.url
# doc.all['id'].click()
You can get doc (document object) with the above code
If you try doc.getElementById ("some-id")
I get an error like the one below.
TypeError: getElementById () takes 1 positional argument but 2 were given
It will appear in IE11
Please Help Me T0T~
p.s The type of problem is different from the suggested answer.
I think I need to fix the error in pywin32.
Related
Can i get some help please i have this code below everything works fine but after a while i receive this error i am using Anaconda Spyder IDE i am not sure what the issue is the script will run but then error out after a few minutes
from polygon import RESTClient
import asyncio
import nest_asyncio
nest_asyncio.apply()
#client = RESTClient(api_key="")
from polygon import WebSocketClient
from polygon.websocket.models import WebSocketMessage
from typing import List
import json
global QuoteList
global TradeList
QuoteList = []
TradeList = []
ws = WebSocketClient(api_key="", feed='socket.polygon.io', market='options',subscriptions=[
"T.O:SPY230210C00408000", "Q.O:SPY230210C00408000",
"T.O:SPY230210P00407000", "Q.O:SPY230210P00407000"])
def handle_msg(msgs: List[WebSocketMessage]):
out_file1 = open("PolygonQuote1.json", "w")
out_file2 = open("PolygonTrade1.json", "w")
#for m in msgs:
m = msgs[len(msgs)-1]
print(m)
if m.event_type == 'Q':
QuoteList.append({'TimeStamp': m.timestamp,
'BidPrice' : m.bid_price,
'BidSize' : m.bid_size,
'AskPrice' : m.ask_price,
'AskSize' : m.ask_size,
'Symbol' : m.symbol})
elif m.event_type == 'T':
TradeList.append({'TimeStamp': m.timestamp,
'Price' : m.price,
'Size' : m.size,
'Symbol' : m.symbol})
json.dump(QuoteList, out_file1, indent=4)
json.dump(TradeList, out_file2, indent=4)
asyncio.run(ws.run(handle_msg))
I believe you might be encountering a bug with Spyder IDE based on the similarity of your error message and the one found here: https://github.com/spyder-ide/spyder/issues/16863
Have you tried using newer versions of the IDE ?
I'm trying to run this code, but it returns an error. I didn't understandig that. What could cause this to occur and how should I fix/troubleshoot the problem?
The code:
import pandas as pd
import spacy
dados = pd.read_csv('treino.csv')
nlp = spacy.load('pt_core_news_sm')
textos_para_tratamento = (titulos.lower() for titulos in dados['title'])
def trata_textos(doc):
tokens_validos = []
for token in doc:
e_valido = not token.is_stop and token.is_alpha
if e_valido:
tokens_validos.append(token.text)
if len(tokens_validos) > 2:
return ' '.join(tokens_validos)
textos_tratados = [trata_textos(doc) for doc in nlp.pipe(textos_para_tratamento,
batch_size= 1000,
n_process = -1)]
The error message:
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child process and you have forgotten to use the proper idiom
in the main module:
if__name__=='__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
The error message is telling you to reorganize your code to only run once in the main module. Since your code isn't runnable as given, I can only suggest the following reorganization:
import pandas as pd
import spacy
def trata_textos(doc):
tokens_validos = []
for token in doc:
e_valido = not token.is_stop and token.is_alpha
if e_valido:
tokens_validos.append(token.text)
if len(tokens_validos) > 2:
return ' '.join(tokens_validos)
if __name__ == '__main__':
dados = pd.read_csv('treino.csv')
nlp = spacy.load('pt_core_news_sm')
textos_para_tratamento = (titulos.lower() for titulos in dados['title'])
textos_tratados = [trata_textos(doc) for doc in nlp.pipe(textos_para_tratamento,
batch_size= 1000,
n_process = -1)]
I wrote the program below,
can = CAN("can0", bitrate=50000, listen_only=True, error_reporting=True)
while True:
msg = can.recv()
print "Msg: ", msg
But it only displays the standard S or Extended X flags even though when I run the command in Terminal to check the network activity, I can see that the error counter is increasing.
import can
import CAN
import time
import logging
#logging.basicConfig(level=logging.DEBUG)
print("Initializing Listener")
can1 = CAN('can0', bitrate=500000, listen_only=True, err_reporting=True)
#print "Bus is : ", can1.bus.get_can_bus()
can1.bus.set_filters(can_filters=[{"can_mask":0x7FF, "can_id":0x00000000, "extended":False}])
CAN_ERR_FLAG = 0x20000000
while 1:
msg = can1.recv()
if (msg.arbitration_id & CAN_ERR_FLAG) == CAN_ERR_FLAG:
print "Can Error Caught"
elif msg.is_error_frame:
print "Finally Error Frame"
How can I read the error-frames of the CAN-bus ?
Things work fine when I use commnad candump -e any,0:0,#FFFFFFFF
Use Python - 3
import binascii
channel_name = "vcan0"
socketID = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
# socketID.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_ERR_FILTER, 0x1FFFFFFF)
error = socketID.bind((channel_name,))
print(binascii.hexlify(socketID.recv(32)))
I want to filter failure messages from output files generated after executing my testcases in Robot Framework. I have tried modules like from robot.api import ExecutionResult but it gives me only only count of Passed and Failed Testcases.
I have also tried other Robot framework Libtraries like import robot.errors to filter out all error messages but didn't get any luck. Below is my code block:
`
#!/usr/bin/python
from robot.api import ExecutionResult
import robot.errors
from robot.result.visitor import ResultVisitor
xmlpath = "<output.xml PATH>"
result = ExecutionResult(xmlpath)
result.configure(stat_config={'suite_stat_level': 2,
'tag_stat_combine': 'tagANDanother'})
stats = result.statistics
print stats.total.critical.failed
print stats.total.critical.passed
print stats.total.critical.passed + stats.total.critical.failed
class FailureCollector(ResultVisitor):
def __init__(self):
self.failures = []
def visit_test(self, test):
if not test.passed:
self.failures += [test]
failure_collector = FailureCollector()
result.visit(failure_collector)
print failure_collector.failures
#the above print gives me all failed testcases as a list Eg: ['test1:My example Testcase1','test2:My example Testcase2' ]`
Any example to get this work done will be very helpful.
I have tried a lot to get my expected output by using Robot Framework APIs but didn't get proper solution. Finally I got my solution by using import xml.etree.ElementTree as ET module. By using xml.etree.ElementTree module I am parsing my robot result.xml file and getting my work done.
`
import xml.etree.ElementTree as ET
import re
tree = ET.parse('<output.xml file Path>')
root = tree.getroot()
testplans = <Testplans as a list>
i = 0
err_dict = {}
for testplan in testplans:
full_err_list = []
err_list = []
for suite_level_1 in root:
try:
if suite_level_1.tag == "suite":
for suite_level_2 in suite_level_1:
if suite_level_2.tag == "suite" and suite_level_2.attrib['name'] == testplan:
for suite_level_3 in suite_level_2:
if suite_level_3.tag == "suite":
for test in suite_level_3:
if test.tag == "test":
for kw_level_5 in test:
if kw_level_5.tag == "kw" and kw_level_5.attrib['name'] == '<specific keyword under which you expect your result(error or Success message >':
for msg in kw_level_5:
if msg.tag == 'msg':
err_str = msg.text
#print err_str
mat = re.match(r'\$\{FinalResult\}\s=\s(.*)',err_str)
if mat and mat.group(1) != 'Succeeded.':
i=i+1
#print mat.group(1), i
err = mat.group(1)
full_err_list.append(err)
if err not in err_list:
err_list.append(err)
except:
print "Errors found"
break
err_dict[testplan] = err_list
print "\n########## "+testplan+" ##########\n"
print "Total no of failures", len(full_err_list)
for err_name in err_list:
print err_name, "===>>", full_err_list.count(err_name)
##The above will print the error name and its count in specific testPlan`
I have this code that does not give any exception, but I do not seem to be receiving events like MapRequests, or ConfigureNotifys:
import xcb
import xcb.xproto as xproto
conn = xcb.connect()
root = conn.get_setup().roots[0].root
eventmask = [xproto.EventMask.SubstructureRedirect, xproto.EventMask.SubstructureNotify]
conn.core.ChangeWindowAttributesChecked(self.root, xproto.CW.EventMask, eventmask)
while True:
e = conn.wait_for_event()
print e
I am testing this in Xephyr.
Am I doing something wrong? And if so, how do I fix it?
edit:
the problem is in incorrect number of parameters: xproto.CW.EventMask indicates that you have one value and you are passing two as [xproto.EventMask.SubstructureRedirect, xproto.EventMask.SubstructureNotify] which should be [xproto.EventMask.SubstructureRedirect|xproto.EventMask.SubstructureNotify]
import xcb
import xcb.xproto as xproto
conn = xcb.connect()
root = conn.get_setup().roots[0].root
conn.core.ChangeWindowAttributesChecked(self.root, xproto.CW.EventMask, [xproto.EventMask.SubstructureRedirect|xproto.EventMask.SubstructureNotify])
while True:
e = conn.wait_for_event()
print e