Python Selenium print elements not element - python

In python Selenium I am attempting to print a list of class_name(meta). When I use browser.find.element only one value is returned. I then amend the script:-
demo = browser.find_elements_by_class_name("meta")
print demo.text
I get the following error:-
Traceback (most recent call last):
File "test.py", line 29, in
print demo.text
AttributeError: 'list' object has no attribute 'text'
I new to python & selenium but I have searched for a solution with no luck.
Thanks in advance for your help.

That is happening because you are not iterating. You forget
for lang in demo:
Example code :-
langs = fire.find_elements_by_css_selector("#gt-sl-gms-menu div.goog-menuitem-content")
for lang in langs:
print lang.text
Hope it will help you :)

Related

Regexpr in python

for printJobString in logfile:
userRegex = re.search('(\suser:\s)(.+?)(\sprinter:\s)', printJobString)
if userRegex:
userString = userRegex.group(2)
pagesInt = int(re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString).group(2))
above is my code, when I run this program in the module I end up getting,
Traceback (most recent call last):
File "C:\Users\brandon\Desktop\project3\project3\pages.py", line 45, in <module>
log2hist("log") # version 2.
File "C:\Users\brandon\Desktop\project3\project3\pages.py", line 29, in log2hist
pagesInt = int(re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString).group(2))
AttributeError: 'NoneType' object has no attribute 'group'
I know this error means the search is returning None but I'm not sure how to handle this case. Any help would be appreciated, very new to python and still learning the basics.
I am writing a program that should print out the number of pages a user has.
180.186.109.129 code: k n h user: luis printer: core 2 pages: 32
is a target string, my python file is trying to create a data file that has one line for each user and contains the total number of pages printed
The reason it happens is because your regexp does not find anything and returns None
re.search('(\spages:\s)(.+?)(\scode:\s)') returns None
use an if statement to test if it's not None before you try to group
for printJobString in logfile:
userRegex = re.search('(\suser:\s)(.+?)(\sprinter:\s)', printJobString)
if userRegex:
userString = userRegex.group(2)
pagesInt = re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString)
if pagesInt:
pagesInt = int(pageInts.group(2))

Feedparser Python Error : KeyError : 'title'

I have seen a lot of KeyCount Errors online but none of them quite match the troubles that I'm having. I am using feed parser to try and create a one run application that accesses all the URLs in a text file and outputs all the entries in each URL. When I run this code :
import feedparser as f
with open('addresses.rtf', 'r') as addresses:
for line in addresses:
d = f.parse(line)
print d["feed"]["title"]
print ""
print d.feed.subtitle
print ""
for post in d.entries:
print post.title
print post.link
print ""
I get this error message :
Traceback (most recent call last):
File "/Users/Josh/Desktop/Feed Parser Python Project/init.py", line 7, in <module>
print d["feed"]["title"]
File "build/bdist.macosx-10.6-intel/egg/feedparser.py", line 375, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'title'
My text file is just a .rtf file that has a URL on each line (3 lines).
If someone could give us a hand please let me know and if you need any extra info please don't hesitate to ask. Any help is welcome. Thank you!
It's hard to tell exactly what is wrong here, but in the general case, any KeyError is because the data you are trying to access is not exactly what you expected. It's best to throw your assumptions out the window and take a close look at the actual data that your code is working with.
For debugging, I would recommend taking a close look at what happens before the error. What is the value of line as you read the file? Is it correct? What is the value of d? Did the call to f.parse(line) result in a valid object?

nameError: global name page_title undefined

I looked at many of the exisiting nameErrors and undefined variable posts and unfortunately was unable to resolve my issue. I am relatively new to programming and especially Python.
I have a dictionary of dictionaries defined in informcast_data.py:
allLinks = {'Send or Edit Messages': {'link':'/InformaCast/admin?cmd=listMessages', 'page_title': 'Messages: Send or Edit Messages'}
I am importing informacast_data.py to users.py:
from informacast.informacast_data import ICData
I then have a function, verify_links which has the following for statement:
for href_link in hrefs:
if href_link.find(ICData.allLinks['page_title']['link'])!=-1:
self.logger.debug("verify_links found=True for " + str(href_link))
found=True
If I leave quotes around page_title I get a keyError and I was told to remove the quotes as it is a variable not a string, I get the nameError when I remove the quotes and I am not sure how to proceed.
below is the full traceback:
Traceback (most recent call last):
File "C:\Users\jesse.sole\Jesse_Workspace\trunk\src\informacast\tests\users.py", line 17, in test_appadmin_role
self.verify_role("appAdmin")
File "C:\Users\jesse.sole\Jesse_Workspace\trunk\src\informacast\tests\users.py", line 78, in verify_role
self.verify_links(sel, roleName)
File "C:\Users\jesse.sole\Jesse_Workspace\trunk\src\informacast\tests\users.py", line 104, in verify_links
if href_link.find(ICData.allLinks[page_title]['link'])!=-1:
NameError: global name 'page_title' is not defined
Thank you in advance for any assistance.
allLinks is a nested dictionary. The top level has no page_title key, so that's why you get a key error:
>>> allLinks = {'Send or Edit Messages': {'link':'/InformaCast/admin?cmd=listMessages', 'page_title': 'Messages: Send or Edit Messages'}}
>>> allLinks['page_title']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'page_title'
There is such a key in the nested dictionary though:
>>> allLinks['Send or Edit Messages']['page_title']
'Messages: Send or Edit Messages'
I think you want to define a variable page_title that has the value 'Send or Edit Messages':
>>> page_title = 'Send or Edit Messages'
>>> allLinks[page_title]['link']
'/InformaCast/admin?cmd=listMessages'
If you loop over the keys in allLinks that would work:
for href_link in hrefs:
for page_title in ICData.allLinks:
if href_link.find(ICData.allLinks[page_title]['link'])!=-1:
self.logger.debug("verify_links found=True for " + str(href_link))
found=True

renderContents in beautifulsoup (python)

The code I'm trying to get working is:
h = str(heading)
# '<h1>Heading</h1>'
heading.renderContents()
I get this error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print h.renderContents()
AttributeError: 'str' object has no attribute 'renderContents'
Any ideas?
I have a string with html tags and i need to clean it if there is a different way of doing that please suggest it.
Your error message and your code sample don't line up. You say you're calling:
heading.renderContents()
But your error message says you're calling:
print h.renderContents()
Which suggests that perhaps you have a bug in your code, trying to call renderContents() on a string object that doesn't define that method.
In any case, it would help if you checked what type of object heading is to make sure it's really a BeautifulSoup instance. This works for me with BeautifulSoup 3.2.0:
from BeautifulSoup import BeautifulSoup
heading = BeautifulSoup('<h1>heading</h1>')
repr(heading)
# '<h1>heading</h1>'
print heading.renderContents()
# <h1>heading</h1>
print str(heading)
# '<h1>heading</h1>'
h = str(heading)
print h
# <h1>heading</h1>

AttributeError: xmlNode instance has no attribute 'isCountNode'

I'm using libxml2 in a Python app I'm writing, and am trying to run some test code to parse an XML file. The program downloads an XML file from the internet and parses it. However, I have run into a problem.
With the following code:
xmldoc = libxml2.parseDoc(gfile_content)
droot = xmldoc.children # Get document root
dchild = droot.children # Get child nodes
while dchild is not None:
if dchild.type == "element":
print "\tAn element with ", dchild.isCountNode(), "child(ren)"
print "\tAnd content", repr(dchild.content)
dchild = dchild.next
xmldoc.freeDoc();
...which is based on the code example found on this article on XML.com, I receive the following error when I attempt to run this code on Python 2.4.3 (CentOS 5.2 package).
Traceback (most recent call last):
File "./xml.py", line 25, in ?
print "\tAn element with ", dchild.isCountNode(), "child(ren)"
AttributeError: xmlNode instance has no attribute 'isCountNode'
I'm rather stuck here.
Edit: I should note here I also tried IsCountNode() and it still threw an error.
isCountNode should read "lsCountNode" (a lower-case "L")

Categories