Selenium Select Input Box that Changes Name Every Session - python-3.x

I'm trying to access a search text box inside of our company's ERP system using Selenium. The screenshot shows the text box and the Xpath of the element.
This is a little tricky, because that Menu Search pop-up isn't really a pop-up. It somehow shows up when a user types Control + M.
By installing ChroPath and testing I've found the text-box always starts with the following string:
txtMenuSearch_Namespace_
I've tried to imitate what's described here, here and here with no luck.
The latest attempt in the snippet of my code looks like this:
menu_search_input_box_elements = driver.find_elements_by_xpath("//*[contains(#id, ‘txtMenuSearch_Namespace_’)]")
for item in menu_search_input_box_elements:
print(item)
I get the following error message:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(#id, ‘txtMenuSearch_Namespace_’)]' is not a valid XPath expression.
In all my attempts to get the syntax right I keep getting this message. Any help in figuring out how to .send_keys() to this field is greatly appreciated.

You get en error because of the ‘’ quotes, replace them with correct ones.
# id starts with txtMenuSearch_Namespace_
menu_search_input_box_elements = driver.find_elements_css_selector("[id^='txtMenuSearch_Namespace_']")
menu_search_input_box_elements = driver.find_elements_by_xpath("//*[contains(#id, 'txtMenuSearch_Namespace_')]")

Related

Checking status/event of icon - Selenium, Python 3.9

With covid and online schooling, it's hard to keep up with my kid keeping up! I'm only a little familiar with Python and less familiar with webstuff and selenium, but I wanted to try to make it easier to check on whether he's finishing his assignments each day by writing a script that (1) goes to the class webpages, (2) looks for the 'Overdue' text in the outer HTML, and (3) does something (e.g., print 'There is an overdue assignment') if the find method succeeds.
I've completed 1 successfully and know how to do part 3, but can't figure out part 2.
I found what I think is the relevant part on the pages with the inspect element:
<i class="icon-minimize" aria-label="This assignment is overdue" title="This assignment is overdue"></i>
And I've tried the following code variations:
overDue = driver.find_element_by_tag_name("This assignment is overdue")
overDue = driver.find_element_by_name("This assignment is overdue")
And I've tried to copy the CSS Selector and use
overDue = driver.find_element_by_class_name("i.icon-minimize:nth-child(1)")
I also tried XPath, but I forget now exactly what my code was. Something like:
overDue = driver.find_element_by_xpath(//*[., text()="This assignment is overdue"])
But all of these return a NoSuchElement exception. Is there something wrong with my syntax or am I using the wrong methods?
Thanks.
overDue = driver.find_element_by_xpath('//*[#title="This assignment is overdue"]')
its title , use #title to validate the value of title attribute
xpath syntax is
//tagname[#attribute="attributevalue"]
so tag_name is i
driver.find_element_by_tag_name("i")
there is no name attribute so you cannot use
driver.find_element_by_name
class is 'icon-minimize' you should not mention tag there:
driver.find_element_by_class_name("icon-minimize")

How to select text from pop up bar

I'm desperate how to get the text of an information message that only appears for a few seconds. The text is
Code for appear is:
<simple-snack-bar class="mat-simple-snackbar ng-star-inserted">
<span>Osoba byla v ROB nalezena.</span><!---->
and this is the selenium code for check the text:
element = driver.find_element_by_xpath(".//simple-snack-bar[#class ='mat-simple-snackbar ng-star-inserted']").get_attribute("text")
But I always get none as an answer. I don't know how to get it anymore. Whether it works at all.

Adding this URL from JIRA as hyperlink to the excel cell does not work, why?

I have the following link:
https://nttdata.atlassian.net/sr/jira.issueviews:searchrequest-csv-current-fields/temp/SearchRequest.csv?jqlQuery=project+%3D+ATHP+AND+issuetype+in+%28story%2C+feature%2C+task%29+AND+Sprint+%3D+1113+AND+%28status+was+not+in++%28DONE%2C+%22BUILD+COMPLETE%22%29+AFTER+%222019%2F01%2F21%22+%29+AND+%28status+was+not+in++%28DONE%2C+%22BUILD+COMPLETE%22%29++BEFORE+%222019%2F01%2F23%22%29&tempMax=1000
Note: It assumes to have an open Jira session for this project. I provided it here in case there is some special character that excel may interpret in a different way.
It executes a Jira Query and downloads the result in a CSV file.
This query is generated by JIRA when trying to export into an excel file the result of the Jira Query Language:
project = ATHP AND issuetype in (story, feature, task) AND
Sprint = 1113 AND (status was not in (DONE, "BUILD COMPLETE") AFTER
"2019/01/21" ) AND (status was not in (DONE, "BUILD COMPLETE")
BEFORE "2019/01/23")
Note: I was trying with a simpler query too based on JIRA request: project = ATHP (search for all issues of project with ID: ATHP) that produce the following query:
https://nttdata.atlassian.net/sr/jira.issueviews:searchrequest-csv-current-fields/temp/SearchRequest.csv?jqlQuery=project+%3DATHP&tempMax=1000
with the same result.
I added as a hyperlink to a cell and when I try to click on the cell, I get the following error:
Unable to open
https://nttdata.atlassian.net/...
Cannot download the information you requested
I thought it may be possible due to the length of the link (396 characters) that has more than 255 characters (see this question), then I created a shortened URL via Bitly, but I get the same error. If I copy and paste the URL directly in Chrome, I get the file downloaded using the original URL or the equivalent Bitly URL.
I also tried to access the hyperlink via VBA script too:
Range("G11").Select
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
But I get the same error.
I have another similar URL created by JIRA that works well as a hyperlink:
https://nttdata.atlassian.net/sr/jira.issueviews:searchrequest-csv-current-fields/39627/SearchRequest-39627.csv?tempMax=1000
One of the differences of this URL is that instead of passing the parameters to the query (JiraQuery) it invokes a filter (saved query) under ID: 39627.
Any suggestion about what is going on here?, for sure there is something in the URL syntax that Excel does not like it, even the navigator accepts it.

Selenium - find element by link text

I am using selenium webdriver on Chrome; python 3 on Windows 10.
I want to scrape some reports from a database. I search with a company ID and a year, the results are a list of links formatted in a specific way: something like year_companyID_seeminglyRandomDateAndDoctype.extension, e.g. 2018_2330_20020713F04.pdf. I want to get all pdfs of a certain doctype. I can grab all links for a certain doctype using webdriver.find_elements_by_partial_link_text('F04') or all of that extension with '.pdf' instead of 'F04', but I cannot figure out a way to check for both at once. First I tried something like
links = webdriver.find_elements_by_partial_link_text('F04')
for l in links:
if l.find('.pdf') == -1:
continue
else:
#do some stuff
But unfortunately, the links are WebElements:
print(links[0])
>> <selenium.webdriver.remote.webelement.WebElement (session="78494f3527260607202e68f6d93668fe", element="0.8703868381417961-1")>
print(links[0].get_attribute('href'))
>> javascript:readfile2("F","2330","2015_2330_20160607F04.pdf")
so the conditional in the for loop above fails.
I see that I could probably access the necessary information in whatever that object is, but I would prefer to do the checks first when getting the links. Is there any way to check multiple conditions in the webdriver.find_elements_by_* methods?
You can try to use below code
links = [link.get_attribute('href') for link in webdriver.find_elements_by_partial_link_text('F04') if link.get_attribute('href').endswith('.pdf")')]
You can also try XPath as below
links = webdriver.find_elements_by_xpath('//a[contains(., "F04") and contains(#href, ".pdf")]')
Andersson's approach seems to work with a slight correction:
if link.get_attribute('href').endswith('.pdf')] rather than if link.get_attribute('href').endswith('.pdf")')], i.e. delete the ").

IMAP fetch() returns command error: BAD [b' Command Argument Error. 12']

I'm having trouble finding examples/troubleshooting tips online, and am not quite sure that I'm interpreting the documentation correctly. Any assistance would be greatly appreciated.
I'm connecting to an e-mail server, and want to read the e-mail subjects, and bodies. I first make my connection like so:
import imaplib
c = imaplib.IMAP4_SSL(hostname, port)
c.login(username, password)
foldername = 'INBOX/SSR'
c.select(str.encode(foldername), readonly = True)
today = datetime.date.today().strftime('%d-%b-%Y')
searchcriteria = '(SENTON '{}')'.format(today)
typ, msg_ids = c.search(None, searchcriteria)
msg_ids = [s.decode('ascii') for s in msg_ids]
for idnumber in msg_ids:
print(c.fetch(idnumber, "(BODY.PEEK[HEADER])"))
The code and works and output looks as expected, up until the last line, at which point, I get
imaplib.error: FETCH command error: BAD [b' Command Argument Error. 12']
My line of thought, and subsequent testing examined the following possible issues:
bytes vs. string. I converted input back to bytes, but the error remained constant
improper syntax: I tried other commands, such as BODY, SUBJECT, and ENVELOPE but still got the same message.
I'm not sure how to interpret the error, and don't really know where to start. Referencing https://www.rfc-editor.org/rfc/rfc3501.html from pp. 102+, I noticed that the values are labeled differently, but don't understand what the issue is with my implementation. How should I interpret the error? What is wrong with my syntax?
P.S. Correct me if I'm wrong, but the c.search shouldn't change my directory, yes? As in, by selecting foldername, I "navigate" to the selected folder, but just searching only returns values and shouldn't change my location?
I encountered the same problem while I tried to list or select a new mailbox - BAD [b' Command Argument Error. 12'], in my case, it didn't work with “Sent Box”, but it worked well with “Outbox”, so the space symbol is the point.
So it worked with c.select('"{}"'.format("Sent Box")...
Hope this information could help you.
Your last line is not correct msg_ids = [s.decode('ascii') for s in msg_ids]
msg_ids is a list with bytes string, not with elements of a list - example: [b'123 124 125']
Change the last line into msg_ids = msg_ids[0].split(b' ') and it will work as expected.

Resources