简体   繁体   中英

List indices must be integers, not tuple

I searched for this problem and tried using the solutions above, but none of them appeared to work.

My current code is:

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

This results in TypeError: indices must be integers, not tuple .

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

So i've completely solved the problem at hand by circumventing the selection issue.

Heres what I did:

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

What this does is first searches the main content on the page (any url could be in G_data). Next it will select [1] which is the focus content, products, images, links etc. It gets rid of all the other stuff. Then there is the part within the brackets, what this does is it selects this piece of content

Gorilla Tape 11m

Now there its not selecting just that one, it selecting all the products on the page. After that there is [0] this the selection of the first product, so if there are 15 products on the page this is 0.

Then you have the ["href"] what this does is take just the data within that keyword, in this case the url for product page in question.

By doing it in this method, you could either select the code and paste and have it look like this:

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

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

If this works

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

that is correct, you just assign an integer as an index. I guess 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM