我有以下代碼:
from bs4 import BeautifulSoup
import requests
root = 'https://br.investing.com'
website = f'{root}/news/latest-news'
result = requests.get(website, headers={"User-Agent": "Mozilla/5.0"})
content = result.text
soup = BeautifulSoup(content, 'lxml')
box = soup.find('section', id='leftColumn')
links = [link['href'] for link in box.find_all('a', href=True)]
for link in links:
result = requests.get(f'{root}/{link}', headers={"User-Agent": "Mozilla/5.0"})
content = result.text
soup = BeautifulSoup(content, 'lxml')
box = soup.find('section', id='leftColumn')
title = box.find('h1').get_text()
with open('headlines.txt', 'w') as file:
file.write(title)
我打算用這段代碼從網站上抓取新聞的 URL,訪問每個 URL,獲取其標題并將它們寫入文本檔案。使用此代碼,我只需在檔案中獲取一個標題并接收AttributeError: 'NoneType' object has no attribute 'find'. 關于這個還能做什么?
uj5u.com熱心網友回復:
在你的 for 回圈中,這里:title = box.find('h1').get_text(), box 是 None (即 NoneType)......這就是為什么你被告知 NoneType 物件沒有屬性 find
這可能正在發生,因為在回圈中的某個時刻,這一行:box = soup.find('section', id='leftColumn')回傳 None
如果 box 回傳 None,則下一行將拋出錯誤。
您可以通過在呼叫 find 之前檢查 box 是否不是 None 來解決此問題。所以這:
box = soup.find('section', id='leftColumn')
title = box.find('h1').get_text()
將更改為
box = soup.find('section', id='leftColumn')
if box is not None:
title = box.find('h1').get_text()
編輯:
您只看到一個標題的原因是您在-w這里: with open('headlines.txt', 'w')
-w將覆寫檔案。我不明白內容,但我猜輸出是最后一個標題
修復:替換-w為-a. 它將在檔案內容中添加“標題”。你可以在這里閱讀:https ://www.w3schools.com/python/python_file_write.asp
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/431617.html
