Looking For Text Of An Element Or Source Of Current Page
I am doing the following in selenium 2/webdrive using python and firefox... I am opening some web pages that I need to check for a specific string - which, if present, means it is
Solution 1:
If you don't know which exception to expect, use empty except
and traceback
:
import traceback
try:
int('string')
except:
traceback.print_exc()
print"returning 0"# will print out an exception and execute everything in the 'except' clause:# Traceback (most recent call last):# File "<stdin>", line 2, in <module># ValueError: invalid literal for int() with base 10: 'string'# returning 0
But from the stack trace you already do know the exact exception name, so use it instead:
from selenium.webdriver.exceptions import NoSuchElementException
try:
#...except NoSuchElementException, err:
#...
UPDATE:
You just get an exception before the try ... except
, here:
product_block = browser.find_element_by_xpath("//div[@class='page_content']");
and not here:
product_name = product_block.find_element_by_xpath("//h2[@class='page_title']");
Solution 2:
That's the solution! Thanks!
Here is the final code, cleaned up a bit to make the result more readable:
#!/usr/bin/env pythonfrom selenium import webdriver
from selenium.webdriver import Firefox as Browser
from selenium.webdriver.support.ui import WebDriverWait
browser = webdriver.Firefox()
defcall_productpage(productlink):
global browser
print'in call_productpage(' + productlink + ')'
browser.get(productlink)
browser.implicitly_wait(1)
product_block = ''try:
product_block = browser.find_element_by_xpath("//div[@class='page_content']");
except:
print'this is NOT a good page - drop it'return0else:
textStr = str(product_block.text)
#print 'page_content:' + str(textStr)print'\nthis is a good page - proceed\n'print'made it past the exception!\n'
product_name = product_block.find_element_by_xpath("//h2[@class='page_title']");
nameStr = str(product_name.text)
print'>>> product_name:' + nameStr + '\n'print"test over!"return1
test1 = call_productpage('https://www.daz3d.com/i/3d-models/-/desk-clocks?spmeta=ov&item=12657')
print'\nTest #1:\n============\n'if test1:
print'\ntest 1 returned true\n'else:
print'\ntest 1 returned false\n'print'\nTest #2:\n============\n'
test2 = call_productpage('https://www.daz3d.com/i/3d-models/-/dierdre-character-pack?spmeta=ov&item=397')
if test2:
print'\ntest 2 returned true\n'else:
print'\ntest 2 returned false\n'print'\n============\n'
And that works just as I need it to.
Again, thanks.
Post a Comment for "Looking For Text Of An Element Or Source Of Current Page"