Python PhantomJS Sending Keys to Text Field Not Working - python

So I'm having a weird problem with PhantomJS where it is continually failing to send text to the text input field. When I run my code with a chrome driver, there is no issue, and everything works as expected.
This is the chat box on twitch streams if you were wondering. Here is some code.
print("Finding chat box...")
typeKeyword = wait_until_visible_by_xpath('//textarea[#placeholder="Send a message"]', browser)
not_working = True
while not_working:
try:
print("Sending keys...")
typeKeyword.send_keys("hi")
not_working = False
except InvalidElementStateException:
sleep(3)
print("Hitting chat button")
chatButton = wait_until_visible_by_xpath('//button[#class="button send-chat-button primary float-right"]', browser)
chatButton.click()
PhantomJS is able to locate the text field, but it keeps getting trapped on the InvalidElementStateException when it is checking whether it can send the keys or not. There should be a small delay because the twitch chat box is usually grayed out for 6-10 seconds before it becomes able to type in it. With the chrome driver, after printing "Sending keys..." about 3 times, the code finishes up and the message is typed. With PhantomJS, however, it prints "Sending keys..." forever.

Refind/"refresh" the element inside the loop:
while not_working:
typeKeyword = browser.find_element_by_xpath('//textarea[#placeholder="Send a message"]')
...

Related

Problem with a code that does not do what it should?

#events.register(events.NewMessage(chats='tubot'))
async def mi_handler(event):
client = event.client
if 'A big' in event.raw_text:
async for message in client.iter_messages('tubot', limit=1, from_user='tubot'):
await message.click(0)
url = event.message.buttons[0][0].url
print(url)
await event.client.send_message('mybot', url.split('=')[1])
This code does something to me that had never happened to me before:
The code should do is: when the message appears in the ¨tubot¨, it should press the button and unlock the url, then a part of that url will send it to my bot called ¨mybot¨.
BUT:
when the message arrives in ´tubot´ the code click on the button and unlock the url, but it does not forward it to ´mybot´.
however when that message with the button already unlocked I manually forward it to "tubot" the code does forward it perfectly to ´mybot´
I have tried the following:
1- await asyncio.sleep(0.2) put an await between clicking on the button and reading the url and nothing didn't work.
2- even separate the code into two parts, one that clicks the button and another that forwards and nothing did not work
3- I made a group I put the code to click on the 'tubot' message and forward it to the group and another code that reads the message in that group with the button already unlocked and forwards the url to 'mybot' and nothing did not work. Even in the group, if I forward the message with the unlocked button, it reads me the url perfectly and it forwards me perfectly to 'mybot' but if it does the code doesn't work

How do you fail a unittest in python if an error message does not pop up on the tested webpage when it should?

I am trying to write a python selenium unittest for a login page. When no username or password is entered before clicking the login button, an error message should pop up telling the user that a username and password is required. However, no error message is displayed on the webpage when you do this so the test should fail. How do I write a test that takes this into account?
You can probably check the size/length/value of the username and password.
If empty then fail the test else pass.
An example would be look like this:
element = driver.find_element_by_xpath('//input[#class="locator"]').get_attribute('value')
if len(element) == 0:
# your actions here

Paramiko Emulating IBM 3151. How do I send the right control keypress

I am using Python 2.7 Paramiko to SSH into a very old system that uses IBM 3151 keymapping. Keyboards back then had an enter or "send" key used to submit responses. In Secure NetTerm, I am able to access this system and the "send" key is mapped to the right ctrl key on the keyboard. For the life of me, I can't figure out how to send the "send" key to the terminal with Paramiko. Below is my test code. I am able to make it through the first few menu options which accept \n, but I am running into a "popup" screen that requires the "send" key. Pressing the right ctrl key works in the emulator, but I can't seem to get anything to work in Paramiko. Any help would be appreciated.
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect('some_server.com', port=22,username='some_user', password='some_password')
except paramiko.SSHException:
print "Connection Failed"
quit()
channel = ssh.invoke_shell(term='IBM-3151', width=80, height=24, width_pixels=0, height_pixels=0)
channel_data = str()
host = str()
srcfile = str()
while True:
if channel.recv_ready():
channel_data += channel.recv(9999)
else:
continue
print channel_data
#Go to store
if channel_data.endswith('> '):# in channel_data:
channel.send('5\n')
# Select a store
if channel_data.endswith(' : '): # in channel_data:
channel.send('0330\n')
if channel_data.endswith('): '): # in channel_data:
channel.send('Y\n')
if 'PRESS SEND TO CONTINUE....' in str(channel_data):
print 'test1' # if statement works
time.sleep(5)
channel.send('^[!l^M') # tried all kinds of stuff here
print 'test2' # script passes to here with no errors.
I'd determine what characters are actually sent by the Send (or Enter) key by
capture all of the characters from a session using script on the AIX system (you might need this for analysis)
in a shell on the AIX system, use cat (to echo) and press control-V before pressing *Enter.
Do that with the working terminal of course. If the data shown by cat does not work with your script, it's possible that there's some initialization done, e.g., putting Secure NetTerm into application mode.

How can we send message by pressing enter in a chat window using splinter?

In a chat window ( watsapp, facebook etc. ) message can be sent by pressing "Enter", How can we achieve that in splinter. I tried submitting the form using browser.execute_script() but its reloading the full page instead.
Also tried browser.get_by_id("id_name").type("something \r") but didn't work.
After experimenting everything finally this code worked for me:
from splinter import Browser
browser = Browser()
script = 'var event = jQuery.Event("keydown"); event.which = 13; event.keyCode = 13; $("#element_id").trigger(event);'
browser.execute_script(script)
I found that some people are using jQuery.Event("keypress") but it didn't worked for me.

Checking if website responds in python using a browser user agent

I am trying to come up with a script to check if a domain name resolves to its IP address via dns; using a python script I wrote.
I want to be able to do this in a few sequential loops, however after trying to run a loop once, the second time i run the script, the names that previously returned a successful dns resolution response, now do not.
Below is my script:
#! C:\Python27
import socket,time
localtime = time.asctime( time.localtime(time.time()) )
def hostres(hostname):
print "Attempting to resolve " + hostname
try:
socket.gethostbyname(hostname)
print "Resolved Successfully!"
except socket.error:
print "Could Not Resolve"
print "*************************************************"
print "Website loop starting.."
print "Local current time :", localtime
print "*************************************************"
print ""
text_file = open("sites.txt", "r")
lines = text_file.readlines()
for line in lines:
hostres(line)
text_file.close()
The contents of the text file are:
www.google.com
en.wikipedia.org
www.youtube.com
us.gamespot.com
I am thinking it is to do with these domains servers recognizing the script as a "bot" rather than a legitimate end-user, would it be correct to assume this?
If so, how can I still check if the dns name resolves by looking up the name of the website (or IP, does not matter) and be able to run this without getting a false reading of "request failed" despite the fact that the service is fully accessible from a browser?
Several problems in this question.
You are not checking if "a website responds" you are testing DNS resolution. All your DNS requests go to a single name server, your LDNS resolver. If all of them resolve, it still says nothing about the status of the website. Also, since you aren't actually talking to these website, they have no way of knowing you're a bot. They can only detect this (based on the HTTP user-agent header) if you make a HTTP request.
Regarding your code problem, you need to trim the newline character before you can do a socket.gethostbyname() on it. Replace socket.gethostbyname(hostname) with socket.gethostbyname(hostname.rstrip()) and you'll be fine.

Categories