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
Related
I have some code that was working, but recently started giving me an error. The problematic section of code looks like this:
if(new_hash != old_hash):
print(new_hash)
print(old_hash)
# Finds content of the most recent post on the list
content = BeautifulSoup(vf_html.find('description').findNext('description').find(text=lambda t: isinstance(t, CData)), 'html.parser')
for img in content.select('img'):
img.replace_with(img['alt'])
content = content.text
new_content_hash = hashlib.md5(str(content).encode('utf-8')).hexdigest()
toSend = (content[:1000] + '') if len(content) > 75 else content
# Finds author of the most recent post on the list
author = vf_xml.find('creator').get_text(strip=True)
author = author.split()[0]
author = author[1:]
This was working fine, but a few hours ago it starting throwing me this error:
Traceback (most recent call last):
File "C:\Users\Taran Mayer\Desktop\CodyBot\scrape.py", line 160, in <module>
scrape()
File "C:\Users\Taran Mayer\Desktop\CodyBot\scrape.py", line 83, in scrape
img.replace_with(img['alt'])
File "C:\Python38\lib\site-packages\bs4\element.py", line 1401, in __getitem__
return self.attrs[key]
KeyError: 'alt'
I don't think I changed anything, and I tried reverting to an earlier, working version of the code, but the error persisted. Can anybody help me find what I'm doing wrong? If I comment out the lines
for img in content.select('img'):
img.replace_with(img['alt'])
the program works, but doesn't do what I want it to.
It seems that some images you want to .replace_with don't have alt= attribute.
You can resolve it with:
for img in content.select('img'):
img.replace_with(img.attrs.get('alt', ''))
this will replace every image (even those missing alt=... attribute)
Or:
for img in content.select('img[alt]'):
img.replace_with(img['alt'])
this will replace only images with alt=... attribute.
I am trying to get the list of assignments due/coursework for all the courses using the Google Classroom API. I am getting a list of courses using the below code :
results = service.courses().list(pageSize = 10).execute()
courses = results.get('courses',[])
Once I get the list of all the courses, I loop over each the course and try to supply the courseID in order to get the list of coursework using courses.courseWork.list method, but I'm getting an error.
I have written the following code :
for course in courses :
print(course['name'])
print "Assignments you have due in this course : "
print course[u'id']
course_work_results = service.courses().courseWork().list().execute()
print course_work_results
Since I am not supplying the courseID anywhere (which I need to know how to do), I get the following error :
Traceback (most recent call last):
File "classroom.py", line 53, in <module>
course_work_results = service.courses().courseWork().list().execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 727, in method
raise TypeError('Missing required parameter "%s"' % name)
TypeError: Missing required parameter "courseId"
The error is caused due to the line
course_work_results = service.courses().courseWork().list().execute()
How to fix this ?
would be helped if the mistake is pointed.
Here Iam trying to create a code for displaying the name of the city state and country by taking Pincode as input, Thanks in advance
import urllib, json
from urllib.request import urlopen
from tkinter import *
global pincode
root=Tk()
frame=Frame(root,width=250,height=250)
frame.grid()
class cal:
def __init__(self):
self.string=StringVar()
entry=Entry(frame,textvariable=self.string)
entry.grid(row=1,column=2,columnspan=6)
but=Button(root,text="submit",command=self.pin)
but.grid()
def pin(self):
pincode=self.string.get()
url = "https://www.whizapi.com/api/v2/util/ui/in/indian-city-by-postal-code?pin="+pincode+"&project-app-key=fnb1agfepp41y49jz6a39upx"
response = urllib.request.urlopen(url)
data = json.loads(response.read().decode('utf8'))
fi=open("neme.txt","w")
fi.write(str(data))
state=data['State']
city=data['City']
area=data['area']
name=Label(frame,text="State:"+state+"City:"+city+"area:"+area)
name.grid(row=3,column=0)
cal()
mainloop()
error being
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
return self.func(*args)
File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Pn_code.py", line 24, in pin
state=data['State']
KeyError: 'State'
Ok. Error tells you that you don't have key named "State" in you dict under data variable. So maybe there isn't also in incomming json.
If in response you get:
{"ResponseCode":0,"ResponseMessage":"OK","ResponseDateTime":"9/3/2016 2:41:25 PM GMT","Data":[{"Pincode":"560103","Address":"nagar","City":"Banalore","State":"nataka","Country":"India"}]}
then you cannot get "State" by using:
data["State"]
you have to do it using:
data["Data"][0]["State"]
and the rest:
data["Data"][0]["City"]
data["Data"][0]["Country"]
Why in this way? Because you have to get nested keys, first key is "Data", using data["Data"] you recieve a list, and because it's one element list, you have to get first item of the list: data["Data"][0]. And at the end under data["Data"][0] you get dict of keys where you can find State, City, Country.
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 :)
I'm trying to use lxml.etree to parse a Wordpress export document (it's XML, somewhat RSS like). I'm only interested in published posts, so I'm using the following to loop through published posts:
for item in data.findall("item"):
if item.find("wp:post_type").text != "post":
continue
if item.find("wp:status").text != "publish":
continue
write_post(item)
where data is the tag that all item tags are found in. item tags contain posts, pages, and drafts. My problem is that lxml can't find tags that have a : in their name (e.g. wp:post_type). When I try item.find("wp:post_type") I get this error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lxml.etree.pyx", line 1279, in lxml.etree._Element.find (src/lxml/lxml.e
tree.c:38124)
File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 210, in f
ind
it = iterfind(elem, path)
File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 200, in i
terfind
selector = _build_path_iterator(path)
File "/usr/lib64/python2.7/site-packages/lxml/_elementpath.py", line 184, in _
build_path_iterator
selector.append(ops[token[0]](_next, token))
KeyError: ':'
I assume the KeyError : ':' refers to the colon in the name of the tag being invalid. Is there some way I can escape the colon so that lxml finds the right tag? Does : have some special meaning in this context? Or am I doing something wrong? Any help would be appreciated.
The : is an XML namespace separator. To escape the colon in lxml, you need to replace it with the namespace URL within curly braces, as in item.find("{http://example.org/}status").text.