How to fix "int' object is not subscriptable" - python

i want to extract 'src' from 'img' tag
I have the code
lists = soup.find(class_="image-container image__pic js-image-pic")
for img in lists:
image = img.find('img')['src']
print (image)
And i got this error 'int' object is not subscriptable

I imagine there is other useful information in the error (you should always put a full error trace), but without this I will say you are likely using .find() when you mean to use .find_all(). One will return a list, and the other will return a single item. I imagine (again, speculating since there is no trace posted) that if you ran:
lists = soup.find_all(class_="image-container image__pic js-image-pic")
for img in lists:
image = img.find('img')['src']
print(image)
It would work as expected. When I have encountered this error that has been the solution for me at least

Related

Python Selenium: Alternative to string formatting for lists?

I am trying to take the value from the input and put it into the browser.find_elements_by_xpath("//div[#class='v1Nh3 kIKUG _bz0w']") function. However, the string formatting surely doesn't work, since it's the list, hence it throws the AttributeError.
Does anyone know any alternatives to use with lists (possibly without iterating over each file)?
xpath_to_links = input('Enter the xpath to links: ')
posts = browser.find_elements_by_xpath("//div[#class='{}']").format(devops)
AttributeError: 'list' object has no attribute 'format'
Looks like the reason of error is that you are placing the format function in the wrong place, so instead of operating on string "//div[#class='{}']" you call it for the list returned by find_elements_by_xpath. Could you please try to replace your code with one of the following lines ?
posts = browser.find_elements_by_xpath("//div[#class='{}']".format(devops))
posts = browser.find_elements_by_xpath(f"//div[#class='{devops}']")

Looping over a list - 'int' object is not subscriptable

I've uploaded a PDF using PyPDF2. Here's my code:
PageNo=list(range(0,pfr.numPages))
for i in PageNo:
pg = writer.addPage(i)
PageNo creates a list of all the page numbers and I'm trying to add each page from the list into a new PDF, but when I run this script, I'm getting 'int' object is not subscriptable. I know it's an error in my for loop, and I'm sure it's obvious, but any insight on my mistake above would be appreciated.
Thanks!
Edit - here's the solution:
for i in list(range(0,pfr.numPages))
pg = pfr.getPage(i)
writer.addPage(pg)
Without seeing more code, like what exactly is pfr.numPages? Where is it created? How is it used? the error is happening because PageNo is being evaluated as an int, so its less likely its an error in your for loop and more likely an error in your list. Assuming pfr.numPages is an array of some type, try this:
for i in range(0, len(pfr.numPages)):
pg = writer.addPage(prf.numPages[i])
However as mentioned before, if PageNo is being evaluated as an int, then pfr.numPages isn't an array or its an array with one element. Pay close attention to the trace if this errors, it will tell you which line, and if it says int is not subscriptable on the line with prf.numPages, then you know that your problem is deeper than this for loop.
I am assuming that writer is a PdfFileWriter object. In that case, you will have to pass a page retrieved from pfr to the writer.addPage method, instead of passing an integer.
for i in pfr.pages:
writer.addPage(i)

Trying to edit private dicom tag

I'm currently trying to edit a private dicom tag which is causing problems with a radiotherapy treatment, using pydicom in python. Bit of a python newbie here so bear with me.
The dicom file imports correctly into python; I've attached some of the output in the first image from the commands
ds = dicomio.read_file("xy.dcm")
print(ds)
This returns the following data:
pydicom output
The highlighted tag is the one I need to edit.
When trying something like
ds[0x10,0x10].value
This gives the correct output:
'SABR Spine'
However, trying something along the lines of
ds[3249,1000]
or
ds[3249,1000].value
returns the following output:
> Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
ds[3249,1000].value
File "C:\Users\...\dataset.py", line 317, in __getitem__
data_elem = dict.__getitem__(self, tag)
KeyError: (0cb1, 03e8)
If I try accessing [3249,1010] via the same method, it returns a KeyError of (0cb1, 03f2).
I have tried adding the tag to the _dicom_dict.py file, as highlighted in the second image:
end of _dicom_dict.py
Have I done this right? I'm not even sure if I'm accessing the tags correctly - using
ds[300a,0070]
gives me 'SyntaxError: invalid syntax' as the output, for example, even though this is present in the file as fraction group sequence. I have also been made aware that [3249,1000] is connected to [3249,1010] somehow, and apparently since they are proprietary tags, they cannot be edited in Matlab, however it was suggested they could be edited in python for some reason.
Thanks a lot
It looks like your dicomio lookup is converting all inputs to hexadecimal.
You could try:
ds[0x3249,0x1000]
This should prevent any forced conversion to hexadecimal.
You can apparently access them directly as strings:
ds['3249', '1000']
However, your issue is that you are trying to access a data element that is nested several layers deep. Based on your output at the top, I would suggest trying:
first_list_item = ds['300a', '0070'][0]
for item in first_list_item['300c', '0004']:
print(item['3249','1000'])
Essentially, a data element from the top level Dataset object can be either a list or another Dataset object. Makes parsing the data a little harder, but probably unavoidable.
Have a look at this for more info.
As Andrew Guy notes in his last comment, you need to get the first sequence item for 300a,0070. Then get the second sequence item from the 300c,0004 sequence in that item. In that sequence item, you should be able to get the 3249,1000 attribute.

unsupported operand type trying to use image as array

def SaveImg(img, path, data):
#image, temp = Image.fromarray((img-bg+127).astype(np.uint8)), data['temps']
img=img.astype(np.uint8)
#y=127
#x=y.astype(np.uint8)
image, temp = Image.fromarray(img-bg), data['temps']
outFile=path+"/%s - %f-%f C.png" % (datetime.now().strftime("%Y-%m-%d %H.%M.%S"), temp[0], temp[1])
image.save(outFile)
print "Saving to", outFile
#time.sleep(5)
This is my function to save images from a camera linked to my computer.
The error I get is:
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
I can't understand where the problem is. Also, I'm changing a code that I did't write and the first line of the function should be the right one but it gives me the same error.
I tried to make some print to see what is wrong but I can't see anything that is NoneType; when I print I don't get NoneType or all zeros arrays.
I see a problem in this line of code:
image, temp = Image.fromarray(img-bg), data['temps']
bg is apparently None. You can't subtract None from something, hence the 'unsupported operand type' error.
From the code you showed it's impossible to deduce what bg should be, or where it is initialized or calculated. From the name I suspect it's a view of the camera without anything in it (i.e., the 'background'). Subtracting a background picture from another picture makes sense, but fails if there is no background picture... Is there a way to view the rest of the code? Is this from some open-source project?

with This below Code i am getting error AttributeError: 'str' object has no attribute 'items' ,

import json
import simplejson
import urllib2
data = urllib2.urlopen('www.example.com/url/where/i/get/json/data').read()
j = ""
j = simplejson.loads(data)
dump_data=simplejson.dumps(j)
for data in j["facets"]:
print data.items()
print "\n----------------\n"
The error message says it all. Clearly j["facets"] is an iterable which contains at least some strings instead of containing some other datatype which has an items method. (maybe you expected a dict)?
Try printing j["facets"] to see what you're actually getting there. Then you might be able to figure out why you're getting a string instead of the expected object (dict).
Title contains the answer
j["facets"] is probably a list of string items

Categories