如何使用 Python 中的 BeautifulSoup 從 body 標籤中抓取所有文字?
網路抓取是一種用於從網站提取資料的強大技術。Python 中一個流行的網路抓取庫是 BeautifulSoup。BeautifulSoup 提供了一種簡單直觀的方法來解析 HTML 或 XML 文件並提取所需資訊。在本文中,我們將探討如何使用 Python 中的 BeautifulSoup 從網頁的 <body> 標籤中抓取所有文字。
演算法
以下演算法概述了使用 BeautifulSoup 從 body 標籤中抓取所有文字的步驟
匯入所需的庫:我們需要匯入 requests 庫來發出 HTTP 請求,以及來自 bs4 模組的 BeautifulSoup 類來解析 HTML。
發出 HTTP 請求:使用 requests.get() 函式向要抓取的網頁傳送 HTTP GET 請求。
解析 HTML 內容:透過傳遞 HTML 內容並指定解析器來建立一個 BeautifulSoup 物件。通常,預設解析器是 html.parser,但您也可以使用 lxml 或 html5lib 等替代方案。
查詢 body 標籤:在 BeautifulSoup 物件上使用 find() 或 find_all() 方法來定位 <body> 標籤。find() 方法返回第一個匹配項,而 find_all() 方法返回所有匹配項的列表。
提取文字:找到 body 標籤後,可以使用 get_text() 方法提取文字內容。此方法返回所選標籤及其所有後代的連線文字。
處理文字:對提取的文字執行任何必要的處理,例如清理、過濾或分析。
列印或儲存輸出:顯示提取的文字或將其儲存到檔案、資料庫或任何其他所需的目標。
語法
soup = BeautifulSoup(html_content, 'html.parser')
這裡,html_content 表示您要解析的 HTML 文件,'html.parser' 是 Beautiful Soup 用於解析 HTML 的解析器。
tag = soup.find('tag_name')
find() 方法在解析的 HTML 文件中找到指定 HTML 標籤(例如,<tag_name>)的第一個匹配項,並返回相應的 BeautifulSoup Tag 物件。
text = tag.get_text()
get_text() 方法從指定的標籤物件中提取文字內容。
示例
以下程式碼將列印 openai 網頁的 body 標籤中的所有文字內容。輸出可能因您選擇抓取的網頁而異。
import requests from bs4 import BeautifulSoup # Make an HTTP request url = 'https://openai.com/' response = requests.get(url) # Parse the HTML content soup = BeautifulSoup(response.content, 'html.parser') # Find the body tag body = soup.find('body') # Extract the text text = body.get_text() # Print the output print(text)
輸出
CloseSearch Submit Skip to main contentSite NavigationResearchOverviewIndexProductOverviewChatGPTGPT-4DALL ·E 2Customer storiesSafety standardsPricingDevelopersOverviewDocumentationAPI referenceExamplesSafetyCompanyAboutBlogCareersCharterSecuritySearch Navigation quick links Log inSign upMenu Mobile Navigation CloseSite NavigationResearchProductDevelopersSafetyCompany Quick Links Log inSign upSearch Submit Your browser does not support the video tag. Introducing the ChatGPT app for iOSQuicklinksDownload on the App StoreLearn more about ChatGPTCreating safe AGI that benefits all of humanityLearn about OpenAIPioneering research on the path to AGILearn about our researchTransforming work and creativity with AIExplore our productsJoin us in shaping the future of technologyView careersSafety & responsibilityOur work to create safe and beneficial AI requires a deep understanding of the potential risks and benefits, as well as careful consideration of the impact.Learn about safetyResearchWe research generative models and how to align them with human values.Learn about our researchGPT-4Mar 14, 2023March 14, 2023Forecasting potential misuses of language models for disinformation campaigns and how to reduce riskJan 11, 2023January 11, 2023Point-E: A system for generating 3D point clouds from complex promptsDec 16, 2022December 16, 2022Introducing WhisperSep 21, 2022September 21, 2022ProductsOur API platform offers our latest models and guides for safety best practices.Explore our productsNew and improved embedding modelDec 15, 2022December 15, 2022DALL ·E now available without waitlistSep 28, 2022September 28, 2022New and improved content moderation toolingAug 10, 2022August 10, 2022New GPT-3 capabilities: Edit & insertMar 15, 2022March 15, 2022Careers at OpenAIDeveloping safe and beneficial AI requires people from a wide range of disciplines and backgrounds.View careersI encourage my team to keep learning. Ideas in different topics or fields can often inspire new ideas and broaden the potential solution space.Lilian WengApplied AI at OpenAIResearchOverviewIndexProductOverviewGPT-4DALL· E 2Customer storiesSafety standardsPricingSafetyOverviewCompanyAboutBlogCareersCharterSecurityOpenAI © 2015 – 2023Terms & policiesPrivacy policyBrand guidelinesSocialTwitterYouTubeGitHubSoundCloudLinkedInBack to top
結論
在本文中,我們討論瞭如何使用 Python 中的 BeautifulSoup 輕鬆地從網頁的 body 標籤中抓取所有文字。透過遵循本文中概述的演算法並使用提供的示例,您可以從您選擇的任何網站提取所需的文字,並執行進一步的處理或分析。