[英]List indices must be integers, not tuple
我搜索了這個問題並嘗試使用上面的解決方案,但它們似乎都不起作用。
我目前的代碼是:
for item in g_data:
print item.contents[1].find_all("a", {"class": "a-link-normal"})[[1], [2], [3]]['href']
這導致TypeError: indices must be integers, not tuple
。
我怎么能解決這個問題呢?我知道這是一個簡單的問題,但我嘗試的解決方案導致它出現並說“不列表”,“不是str”或“不是元組”。
所以我通過規避選擇問題完全解決了手頭的問題。
繼承人我做了什么:
對於g_data中的項目:print item.contents [1] .find_all(“a”,{“class”:“a-link-normal s-access-detail-page a-text-normal”})[0] [“ HREF“]
這樣做首先搜索頁面上的主要內容(任何網址都可以在G_data中)。 接下來它將選擇[1]這是焦點內容,產品,圖像,鏈接等。它擺脫了所有其他的東西。 然后是括號內的部分,它的作用是選擇這段內容
大猩猩膠帶11米
現在它沒有選擇那個,它選擇頁面上的所有產品。 之后有[0]這是第一個產品的選擇,所以如果頁面上有15個產品,則為0。
那么你有[“href”]這樣做只需要該關鍵字中的數據,在這種情況下是相關產品頁面的網址。
通過在此方法中執行此操作,您可以選擇代碼並粘貼,並使其如下所示:
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”]
或者你可以找到一種方法,在一行代碼中列出XY中的所有產品,這應該不難。
如果這樣的話
print item.contents[1].find_all("a", {"class": "a-link-normal"})[1]['href']
這是正確的,你只需指定一個整數作為索引。 我想你想這樣做。
for item in g_data:
print [item.contents[1].find_all("a", {"class": "a-link-normal"})[index]['href'] for index in [1,2,3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.