[問題] 請問CookieJar如何取某NAME值給變數

看板Python作者 (霹靂狗)時間5年前 (2020/03/12 13:19), 5年前編輯推噓2(206)
留言8則, 2人參與, 5年前最新討論串1/1
請問,我透過browser_cookie3模組撈出Chrome內的指定Domain Cookie值後 透過下面這段可以整齊的顯示,但要怎麼在一堆Cookie中取出指定NAME的值呢 for item in cookies: print(item.name+"="+item.value) 找到的教學都是撈出CookieJar後就直接餵給requests 但我只是要取值出來記錄而已 謝謝 後續找到一段語法,但是要運用卻出現 AttributeError: 'CookieJar' object has no attribute 'find' def getmidstring(html, start_str, end): start = html.find(start_str) if start >= 0: start += len(start_str) end = html.find(end, start) if end >= 0: return html[start:end].strip() print(getmidstring(cookies,"NAME=\"","\"")) 成功解出來了,只是不知是不是最佳解 for item in cookies: if(getmidstring(item.name+"="+item.value,"NAME=","\"")!=None): key=item.value -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.142.76.60 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1583990367.A.46C.html ※ 編輯: piligo (220.142.76.60 臺灣), 03/12/2020 13:48:29 ※ 編輯: piligo (220.142.76.60 臺灣), 03/12/2020 18:55:47

03/13 00:19, 5年前 , 1F
把它變成一個 dict 然後再取 key 就行了
03/13 00:19, 1F

03/13 00:20, 5年前 , 2F
myDict = {item.name:item.value for item in cookies }
03/13 00:20, 2F

03/13 00:21, 5年前 , 3F
print(myDict.keys())
03/13 00:21, 3F

03/13 00:22, 5年前 , 4F
再看你要取出哪個 key (就是你要的 item.name, 或 NAME)
03/13 00:22, 4F

03/13 00:22, 5年前 , 5F
print(myDict[NAME])
03/13 00:22, 5F

03/13 00:29, 5年前 , 6F

03/13 01:05, 5年前 , 7F
感謝~成功 程式碼又縮短了許多 ^^
03/13 01:05, 7F

03/17 01:33, 5年前 , 8F
^^
03/17 01:33, 8F
文章代碼(AID): #1UQSPVHi (Python)
文章代碼(AID): #1UQSPVHi (Python)