[問題] 請教Beautifulsoup擷取文字的問題

看板Python作者 (Nothing)時間1年前 (2022/07/01 17:03), 1年前編輯推噓4(403)
留言7則, 4人參與, 1年前最新討論串1/1
各位好 我是程式小白,最近買了堂新手入門課程 嘗試寫了個PTT爬蟲 並且只會print出有包含關鍵字的文章及連結 目前是可以執行,但是有以下圖片的問題 想要只截取出網址的部分(圖片紅框部分),卻找不到辦法 https://imgur.com/a/rYe0880 以下是程式碼 import requests from bs4 import BeautifulSoup import time #這邊以上是基本配置 # today = time.strftime('%m/%d').lstrip('0') url = 'https://www.ptt.cc/bbs/Steam/index.html' keyword = '特' articles = [] for x in range(10): resp = requests.get(url) soup = BeautifulSoup(resp.text, 'html5lib') paging = soup.find('div', 'btn-group btn-group-paging').find_all('a')[1]['href'] rents = soup.find_all('div', 'r-ent') for rent in rents: title = rent.find('div', 'title').text.strip() count = rent.find('div', 'nrec').text.strip() date = rent.find('div', 'date').text.strip() link = rent.find('a') article = '%s %s %s %s' % (date, title, count, link) try: if keyword in title: articles.append(article) except: if count == '爆': articles.append(article) url = 'https://www.ptt.cc' + paging if len(articles) != 0: for article in articles: print(article) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.213.213 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1656666233.A.DF4.html

07/01 18:23, 1年前 , 1F
link['href']
07/01 18:23, 1F

07/01 18:25, 1年前 , 2F
用一般字串處理的方式就好了吧
07/01 18:25, 2F

07/01 18:25, 1年前 , 3F
link.get("href", "err:no_href")
07/01 18:25, 3F
我有嘗試過改成link['href'].但是程式會出錯 測試的時候有試過print(link['href']),這樣是正常的 但是當我想要放到 article = '%s %s %s %s' % (date, title, count, link['href']) 執行就會錯誤 TypeError: 'NoneType' object is not subscriptable ※ 編輯: onlyAPU (125.228.213.213 臺灣), 07/01/2022 18:36:03

07/02 11:20, 1年前 , 4F
rent.find傳回None就會Error
07/02 11:20, 4F
今天早上將程式碼改成下面就可以了。謝謝 try: link = rent.find('a')['href'] except: link = None #如果遇到刪文href會是None type,所以要賦予一個值,才可以用APPEND ※ 編輯: onlyAPU (125.228.213.213 臺灣), 07/02/2022 12:46:28

07/02 13:23, 1年前 , 5F
比較好的方式是用if處理; link_tag =rent.find("a")
07/02 13:23, 5F

07/02 13:24, 1年前 , 6F
link= "" if link_tag is None else link_tag["href"]
07/02 13:24, 6F

07/02 15:46, 1年前 , 7F
謝謝,來研究一下f'的用法,有時候直接輸出變數會錯誤
07/02 15:46, 7F
文章代碼(AID): #1YlhXvtq (Python)