List indices must be integers, not tuples

I searched for this problem and tried the above solutions but none of them worked.

My current code:

 for item in g_data:
     print item.contents[1].find_all("a", {"class": "a-link-normal"})[[1], [2], [3]]['href'] 

      

The result is TypeError: indices must be integers, not tuple

.

How can I fix this? I know this is a simple problem, but the solutions I've tried result in it coming up or saying "not a list", "not str" or "not a tuple".

+3


source to share


2 answers


So, I solved the problem completely by bypassing the selection problem.

Here's what I did:

for an item in g_data: print item.contents [1] .find_all ("a", {"class": "a-link-normal s-access-detail-aa-text-normal"}) [0] ["href "]

What it means is looking for the main content on the page first (any url can be in G_data). Then it will select [1], which is focus content, products, images, links, etc. He gets rid of everything else. Then there is a part in brackets that does it, it selects this piece of content

Gorilla 11m



Now it doesn't select only the one that selects all products on the page. After that there is [0] this selection of the first product, so if there are 15 products on the page, it is 0.

Then you have a ["href"] that does it only take the data inside that keyword, in this case the URL for the product page.

Once done in this method, you can select the code and paste and look like this:

print item.contents [1] .find_all ("a", {"class": "a-link-normal s-access-detail-aa-text-normal"}) [0] ["href"] print item. contents [1] .find_all ("a", {"class": "a-link-normal s-access-detail-aa-text-normal"}) [1] ["href"] print item.contents [1 ] .find_all ("a", {"class": "a-link-normal s-access-detail-aa-text-normal"}) [2] ["href"]

Or you can find a way to list all products from XY in one line of code, which shouldn't be hard.

0


source


If it works

print item.contents[1].find_all("a", {"class": "a-link-normal"})[1]['href']



this is correct, you are just assigning the integer as the index. I think you want to do this.

for item in g_data:
     print [item.contents[1].find_all("a", {"class": "a-link-normal"})[index]['href'] for index in [1,2,3]]

      

-1


source







All Articles