I was searching for a way to do this a lot of times but I didn't find any solution.
I'll show you what I mean:
def test_288_try_this(self):
try:
do_something()
except NoSuchElementException:
self.assertTrue(False, "This test fails bigger than you.")
I'm doing it that way, Of course is working buy I feel is not the correct way. I'd like to know if there is any kind of "self.assertFail(fail_message)" or some like that.
Thanks!
Python:
If you want to verify whether the particular web element is present on a page after navigation. You can use the below method.
self.assertTrue(element, msg='Element name is not present after naviagting to x page')
Related
i am trying to execute this very short code that took out from my bigger code because i was having problems with it. I was able to reproduce the problem (it gave the exact same error).
BACKGROUND INFO: i am just trying to get the first sentence out of this wikipedia search. but because the word i am searching for (kip, means chicken in Dutch) has a wide variety of meanings or something i get an error. i want to bypass this error using try: except: but it keeps displaying the error message anyway.
here is the code that just doesnt seem to work:
import wikipedia
wikipedia.set_lang('nl')
try:
summry = wikipedia.summary('kip', sentences=1)
print(summry + "\n")
except:
print("error")
i have tried replacing except: with this
except wikipedia.exceptions.DisambiguationError:
but it still doesnt work :( it always displays the error code regradless and prints "error" afterwards
/opt/virtualenvs/python3/lib/python3.8/site-packages/wikipedia/wikipedia.py:389:
GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML
parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on
another system, or in a different virtual environment, it may use a different parser and behave
differently.
The code that caused this warning is on line 389 of the file
/opt/virtualenvs/python3/lib/python3.8/site-packages/wikipedia/wikipedia.py. To get rid of this
warning, pass the additional argument 'features="html5lib"' to the BeautifulSoup constructor.
lis = BeautifulSoup(html).find_all('li')
error
i am using repl.it to program this
if anyone has any idea about why it keeps displaying the error anyway please please let me know :D
First of all, thank you all for commenting :D it helped a lot
At the end the solution that worked for me was inspired from Askold Ilvento's comment
although
with warnings.catch_warnings(): warnings.simplefilter("ignore")
didn't work when i adapted it a little bit it did the job!
this is the code that solved the problem and allowed me to ignore what was actually a warning (not an exception) and stop displaying it
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
i just added this at the start of the script and it solved the problem :D
once again all the credit for this code goes to Askold Ilvento i just had to add a little bit to it to make it work
There are a bunch of people on this site have had a similar questions to mine, but I can't seem to find one that has solved it the way I want it to.
I'm trying to get a password out of a database so that I can send an email automatically. To do this, I am calling Credential.objects.get(username='foo').password.
This is where I get the error.
What's really weird about this is I already had access to this database in a python console, and I've created a row in it. I have no clue why it's not showing up!
Other people seem to recommend doing the following:
try:
Credential.objects.get(username='foo').password
except Exception as e:
return None
All that this is doing is making sure the program doesn't return an error.
This doesn't help me because this can't fail.
An email must be sent and this call must get it.
I'm almost certain I'm calling the right function for this, but I've been wrong before. Any help on this would be greatly appreciated.
credential.py (not putting up max_length for security reasons):
import d_models as models
class Credential(models.Model):
username = models.CharField()
password = EncryptedCharField()
Following may clear your concept.
from django.core.exceptions import ObjectDoesNotExist
try:
Credential.objects.get(username='foo').password
except ObjectDoesNotExist:
#If User with username='foo' does not exist in database then it will comes #in exception.
#Even if there are multiple entries in database with username='foo' then also it will give you error for this you need to use another exception.
return "What ever you want to return on exception"
Or else you can try:
python manage.py shell
for user in Credentials.objects.all():
print username
print password
And check what are the users are available in your database(configured in settings.py file).
After two hours of looking at my code, I realized that I am an idiot.
One thing that I left out was that I ran this function in a test case, which spins up separate blank test databases. The function call wouldn't work because it was trying to get at the wrong database!
To fix this I just called: ./manage.py dumpdata --format json --indent 4 -o ./full/path/to/file/credential.json and put fixtures = ['./full/path/to/file/credential.json'] at the top of the test class. Thanks to everyone for the suggestions! Hopefully I didn't waste too much of your time!
Hi i've been trying to learn selenium.
The problem i am having is that an element isn't being detected. The html code i am working with is highlighted right here https://gyazo.com/a76608d4c4e9fc3bd29412436604c173. That line of code stopped my program and gave me the error https://gyazo.com/72fc72e6488578c9c2a50b71311602c5.
The code i am using to detect for the textarea class is
comment=driver.find_element_by_xpath("//form[#class='comment-form no-border-top']/div/*[1]") or driver.find_element_by_xpath("//form[#class='comment-form']/div/*[1]")
because sometimes it switches between comment-form no border and comment form.
My idea is to use a conditional assignment operator check for example if(comment!=none): do something, but to my understanding python doesn't allow this.
any suggestions on what to do and whether my xpath is a reliable method?
If the problem you're trying to solve is actually conditional assignment, there are two different things you might want to know.
The first is that you can do:
if(comment!=none)
you just have to do it like this:
comment = Foo()
if comment is None:
comment = Bar()
Second, maybe you want to try assigning comment if the first call throws an error rather than just being None. If so, try using try!
from selenium.common.exceptions import NoSuchElementException
try:
comment = driver.find_element_by_xpath("//form[#class='comment-form no-border-top']/div/*[1]")
except NoSuchElementException:
comment = driver.find_element_by_xpath("//form[#class='comment-form']/div/*[1]")
I am a beginner python programmer, and I am working on a selenium project in python 2.7.
I have a generic scraper script, that basically outlines what I want to do with all the websites that I visit. However, because of the nature of the data that I want to grab, I can't run the same code on each site-- each site needs to run it's own individual code.
I have attempted to solve this by importing inside of an if statement, and this is the solution I came up with:
site = False
if source_website == "Website A":
from website_a import *
site = True
elif source_website == "Website B":
from website_b import *
site = True
else:
print "This is not an acceptable website!"
if site == True:
# main code block
driver = driver_setup(chrome)
driver.get(source_website_URL)
stuff_to_save = do_some_stuff(driver)
xml_file(stuff_to_save)
driver.quit()
where the website_a and website_b modules both have functions named do_some_stuff, and they do stuff specific to the website that they're on. Now, this seems to work, for the most part. I also seem to be able to extend functionality to any number of websites, given that I program a module called website_c with the function do_some_stuff, and add that to the conditional import.
So, my question is, is this a good idea? Is there a better way to do something like this?
I have literally never seen anyone wrap import statements inside of if statements like this-- and generally, if no one seems to do it, there's usually a good reason why.
In general, from somewhere import * is not a good idea due to namespace pollution. If you want the website-specific code in separate modules, why not do something like
import importlib
website_modules = {'Website A': 'website_a', 'Website B': 'website_b'}
# ...
website = importlib.import_module(website_modules[source_website])
# use with website.function_name
Explore the page object model pattern (http://code.google.com/p/selenium/wiki/PageObjects). You should model each page as a unique entity, then have some logic that determines what page type you are displaying (either explicitly by having you specify it or implicitly by inspecting the URL and the contents of the page) and then expose the methods to capture the data you need on those objects rather than working directly with the webdriver instance. You should ultimately aim for something like:
for page_identifier in ['page1', 'page2', 'page3']:
page = navigate_to(page_identifier)
extracted_data = page.get_data()
xml_file.write(extracted_data)
What is meant by "using the EAFP principle" in Python? Could you provide any examples?
From the glossary:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
An example would be an attempt to access a dictionary key.
EAFP:
try:
x = my_dict["key"]
except KeyError:
# handle missing key
LBYL:
if "key" in my_dict:
x = my_dict["key"]
else:
# handle missing key
The LBYL version has to search the key inside the dictionary twice, and might also be considered slightly less readable.
I'll try to explain it with another example.
Here we're trying to access the file and print the contents in console.
LBYL - Look Before You Leap :
We might want to check if we can access the file and if we can, we'll open it and print the contents. If we can't access the file we'll hit the else part. The reason that this is a race condition is because we first make an access-check. By the time we reach with open(my_file) as f: maybe we can't access it anymore due to some permission issues (for example another process gains an exclusive file lock). This code will likely throw an error and we won't be able to catch that error because we thought that we could access the file.
import os
my_file = "/path/to/my/file.txt"
# Race condition
if os.access(my_file, os.R_OK):
with open(my_file) as f:
print(f.read())
else:
print("File can't be accessed")
EAFP - Easier to Ask for Forgiveness than Permission :
In this example, we're just trying to open the file and if we can't open it, it'll throw an IOError. If we can, we'll open the file and print the contents. So instead of asking something we're trying to do it. If it works, great! If it doesn't we catch the error and handle it.
# # No race condition
try:
f = open(my_file)
except IOError as e:
print("File can't be accessed")
else:
with f:
print(f.read())
I call it "optimistic programming". The idea is that most times people will do the right thing, and errors should be few. So code first for the "right thing" to happen, and then catch the errors if they don't.
My feeling is that if a user is going to be making mistakes, they should be the one to suffer the time consequences. People who use the tool the right way are sped through.