logo
Loading...

在定位問題:何時才需要索引值?在迴圈時是什麼原因可以不需添加 - Cupoy

想請教一下為什麼在單獨讀取時,需要索引,但在回圈內不需要也能夠讀取到全部資料import reque...

索引,迴圈,定位

在定位問題:何時才需要索引值?在迴圈時是什麼原因可以不需添加

2021/10/01 上午 06:22
PTT(批踢踢)網路爬蟲程式實作練習
Allen Chen
觀看數:14
回答數:1
收藏數:0
索引
迴圈
定位

想請教一下 為什麼在單獨讀取時,需要索引,但在回圈內不需要也能夠讀取到全部資料 import requests from bs4 import BeautifulSoup url = 'https://www.ptt.cc/bbs/NBA/index.html' resp = requests.get(url) soup = BeautifulSoup(resp.text, "html5lib") arti = soup.find_all(class_ = "r-ent") (fc>#93c47d:#單獨讀取時,需要索引#ff0000:print(arti[0].find(class_ = "author").text) print(arti[0].find(class_ = "title").text.replace('\n','').replace('\t','')) print(arti[0].find(class_ = "date").text) #93c47d:#回圈內不需要也能夠讀取到全部資料#ff0000:for content in arti: author = content.find(class_ = "author").text title = content.find(class_ = "title").text.replace('\n','').replace('\t','') date = content.find(class_ = "date").text print(f"{author} {title} {date}")

回答列表

  • 2021/10/02 下午 10:47
    Ray
    贊同數:0
    不贊同數:0
    留言數:0

    您好,請問您說的索引是指程式碼中的arti嗎?如果是的話,迴圈並不是不需要索引,而是『for content in arti』這段就已經將索引帶入迴圈當中了,希望這有幫助到您~ 若是仍有疑問或該回答並未解決您的問題的話,歡迎繼續提問喔~