I'm using web driver to automate a test case. I'm trying to verify the text present in the page or not. I'm doing the following, but I don't know how to verify the textPresent is what I'm actually looking for.
textPresent = driver.find_element_by_xpath ("//span/p")
then when I did textPresent.text it's giving the text "An error occured processing Order" where I'm actually looking for "Successfuly added to processing" in the same xpath location. So in this situation, I want to fail the test case. How do i do that?
We should include a check point to verify the equality of actual text with expected :
expectedText = "Successfuly added to processing";
textPresent = driver.find_element_by_xpath ("//span/p");
if textPresent != expectedText
<Write fail condition here e.g. return "Fail" or raise Exception("Fail")>
Related
Information
In my current project I work in the Magento Cloud area, and define my test cases using Python + Selenium. Currently I used Chrome with the webdriver 78x in the first development stage.
On the page is a block with text that I try to verify. The source works correctly according to one view, I just define an assert at the end which secures the VErification.
But now the problem, the assert becomes active every time, although the text is correct. I can't really explain this anymore.
I get the following message:
self.assertEqual([], self.verificationErrors)
AssertionError: Lists differ: [] != ["'This[99 chars] that\\n you give the Sto[183 chars]it."]
Second list contains 1 additional elements.
First extra element 0:
"'This[99 chars] that\\n you give the Store while using this we[441 chars]ges.' != 'This[99 chars] that you give the Store while using this webs[431 chars]ges.'\nDiff is 1188 characters long. Set self.maxDiff to None to see it."
- []
+ ["'This[99 chars] that\\n you give the Store while using this we[441 "
+ "chars]ges.' != 'This[99 chars] that you give the Store while using this "
+ "webs[431 chars]ges.'\n"
+ 'Diff is 1188 characters long. Set self.maxDiff to None to see it.']
----------------------------------------------------------------------
Ran 11 tests in 117.076s
FAILED (failures=1)
The Source
def test_untitled_test_case(self):
driver = self.driver
driver.get("https://URL-TO-PROJECT.com")
self.assertEqual("This privacy policy sets out how this website (hereafter \"the Store\") uses and protects any information that\n you give the Store while using this website. The Store is committed to ensuring that your privacy is protected.\n Should we ask you to provide certain information by which you can be identified when using this website, then\n you can be assured that it will only be used in accordance with this privacy statement. The Store may change\n this policy from time to time by updating this page. You should check this page from time to time to ensure\n that you are happy with any changes.", driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Privacy and Cookie Policy'])[3]/following::p[1]").text)
question
Am I correct that my query is wrong?
Am I asking too much text?
Is it Magento?
I have a list of first name and last that is supposed to be used to compose website links. But sometimes some users don't always follow the naming rule and finally, their website name doesn't match correctly with the expected one.
Here is an example: lest's say the name is John and last name is Paul. In this case, the website URL should be johnpaul.com. But sometimes, use put johnpaul.com or pauljohn.com, or john-paul.com.
I would like to automatize some processes on these websites. The vast majority of them are correct, but some not. When it is not correct, I just google the expected URL and it is generally the first or second result I get on google.
I was asking myself if it is possible to make a Google request and check the 2 or 3 first links with python to get the actual URL. Any idea on how to make something like this?
my code now looks like this:
for value in arr:
try:
print requests.get(url).status_code, url
except Exception as e:
print url, " is not available"
I'd go with endswith()
string = "bla.com"
strfilter = ('.com', '.de') # Tuple
if string.endswith(strfilter):
raise "400 Bad Request"
this way you filter out the .com .net etc errors.
I am trying to migrate a forum to phpbb3 with python/xpath. Although I am pretty new to python and xpath, it is going well. However, I need help with an error.
(The source file has been downloaded and processed with tagsoup.)
Firefox/Firebug show xpath: /html/body/table[5]/tbody/tr[position()>1]/td/a[3]/b
(in my script without tbody)
Here is an abbreviated version of my code:
forumfile="morethread-alte-korken-fruchtweinkeller-89069-6046822-0.html"
XPOSTS = "/html/body/table[5]/tr[position()>1]"
t = etree.parse(forumfile)
allposts = t.xpath(XPOSTS)
XUSER = "td[1]/a[3]/b"
XREG = "td/span"
XTIME = "td[2]/table/tr/td[1]/span"
XTEXT = "td[2]/p"
XSIG = "td[2]/i"
XAVAT = "td/img[last()]"
XPOSTITEL = "/html/body/table[3]/tr/td/table/tr/td/div/h3"
XSUBF = "/html/body/table[3]/tr/td/table/tr/td/div/strong[position()=1]"
for p in allposts:
unreg=0
username = None
username = p.find(XUSER).text #this is where it goes haywire
When the loop hits user "tompson" / position()=11 at the end of the file, I get
AttributeError: 'NoneType' object has no attribute 'text'
I've tried a lot of try except else finallys, but they weren't helpful.
I am getting much more information later in the script such as date of post, date of user registry, the url and attributes of the avatar, the content of the post...
The script works for hundreds of other files/sites of this forum.
This is no encode/decode problem. And it is not "limited" to the XUSER part. I tried to "hardcode" the username, then the date of registry will fail. If I skip those, the text of the post (code see below) will fail...
#text of getpost
text = etree.tostring(p.find(XTEXT),pretty_print=True)
Now, this whole error would make sense if my xpath would be wrong. However, all the other files and the first numbers of users in this file work. it is only this "one" at position()=11
Is position() uncapable of going >10 ? I don't think so?
Am I missing something?
Question answered!
I have found the answer...
I must have been very tired when I tried to fix it and came here to ask for help. I did not see something quite obvious...
The way I posted my problem, it was not visible either.
the HTML I downloaded and processed with tagsoup had an additional tag at position 11... this was not visible on the website and screwed with my xpath
(It probably is crappy html generated by the forum in combination with tagsoups attempt to make it parseable)
out of >20000 files less than 20 are afflicted, this one here just happened to be the first...
additionally sometimes the information is in table[4], other times in table[5]. I did account for this and wrote a function that will determine the correct table. Although I tested the function a LOT and thought it working correctly (hence did not inlcude it above), it did not.
So I made a better xpath:
'/html/body/table[tr/td[#width="20%"]]/tr[position()>1]'
and, although this is not related, I ran into another problem with unxpected encoding in the html file (not utf-8) which was fixed by adding:
parser = etree.XMLParser(encoding='ISO-8859-15')
t = etree.parse(forumfile, parser)
I am now confident that after adjusting for strange additional and multiple , and tags my code will work on all files...
Still I will be looking into lxml.html, as I mentioned in the comment, I have never used it before, but if it is more robust and may allow for using the files without tagsoup, it might be a better fit and save me extensive try/except statements and loops to fix the few files screwing with my current script...
regarding this code from python-blogger
def listposts(service, blogid):
feed = service.Get('/feeds/' + blogid + '/posts/default')
for post in feed.entry:
print post.GetEditLink().href.split('/')[-1], post.title.text, "[DRAFT]" if is_draft(post) else ""
I want to know what fields exist in feed.entry but I'm not sure where to look in these docs to find out.
So I dont just want an answer. I want to know how I should've navigated the docs to find out for myself.
Try dir(field.entry)
It may be useful for your case.
It's a case of working through it, step by step.
The first thing I did was click on service on the link you sent... based on service = feed.Get(...)
Which leads here: http://gdata-python-client.googlecode.com/hg/pydocs/gdata.service.html
Then looking at .Get() it states
Returns:
If there is no ResultsTransformer specified in the call, a GDataFeed
or GDataEntry depending on which is sent from the server. If the
response is niether a feed or entry and there is no ResultsTransformer,
return a string. If there is a ResultsTransformer, the returned value
will be that of the ResultsTransformer function.
So guessing you've got a GDataFeed - as you're iterating over it:, and a quick google for "google GDataFeed" leads to: https://developers.google.com/gdata/jsdoc/1.10/google/gdata/Feed
I am creating a Python script with Selenium. I want to run a specific test that checks the default text of a textbox when the page loads up. Below is my code.......
try:
self.assertEqual("Search by template name or category..", sel.get_text("//table[#id='pluginToolbarButton_forms']/tbody/tr[2]/td[2]/em"))
logging.info(' PASS: text box text is correct')
except Exception:
logging.exception(' FAIL: text box text is incorrect')
Here is my error......
self.assertEqual("Search by template name or category..", sel.get_text("//table[#id='pluginToolbarButton_forms']/tbody/tr[2]/td[2]/em"))
File "C:\Python27\lib\unittest\case.py", line 509, in assertEqual
assertion_func(first, second, msg=msg)
File "C:\Python27\lib\unittest\case.py", line 502, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: 'Search by template name or category..' != u'Submitter Requests'
Am I using the wrong function?
Your AssertionError states that the assertion you tried (that's the self.assertEqual(...) in your first code example) failed:
AssertionError: 'Search by template name or category..' != u'Submitter Requests'
This assertion explains that the string 'Search by template name or category' is different from 'Submitter Requests', which is correct ... the strings are, in fact, different.
I would check your second parameter to self.assertEqual and make sure that you're selecting the right feature.
This looks like you are using the right function, but perhaps you are not running your tests in the correct fashion.
The problem seems to be that you are not selecting the right element to compare with. You are basically telling the program to match that "Search by template name or category.." is equal to the contents of whatever is in:
//table[#id='pluginToolbarButton_forms']/tbody/tr[2]/td[2]/em
Apparently, the contents are "Submitter Requests", i.e not what you would expect, so the test fails (as it should). You might not be selecting the right element with that XPath query. Maybe a CSS query would be best. You can read about element selectors in the Selenium documentation.
Keep an eye open for a pitfall as well: the text returned by Selenium is a Unicode object, and you are comparing it against a string. This might not work as expected on special characters.