首先安裝它。 我們將使用一個簡單的示例html smippet:pip install beautifulsoup4
<code class="html"><html> <head> <title>My Webpage</title> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <a href="https://www.example.com">Link to Example</a> </body> </html></code>
>導入beautifutsoup:
<code class="python">from bs4 import BeautifulSoup</code>
>
<code class="python">html = """<html>...</html>""" # Your HTML string goes here. soup = BeautifulSoup(html, 'html.parser')</code>>
soup.find()
soup.find('h1')
<h1>This is a heading</h1>
soup.find_all()
。 soup.find_all('p')
<p>This is a paragraph.</p>
tag.name
找到所有匹配的標籤。 將返回一個包含soup.find('h1').name
的列表。 'h1'
tag.text
:soup.find('h1').text
獲取標籤名稱。 'This is a heading'
返回tag.get('attribute')
soup.find('a').get('href')
'https://www.example.com'
:tag.attrs
獲取屬性的值。
返回。 :>>將所有屬性作為字典獲取。 >在網絡上與python刮擦中美麗湯的常見用例有什麼常見的用例?從網站上提取數據:soup.select()
>的CSS選擇器進行功能強大而簡潔的選擇。 這通常比嵌套find()
調用更有效。例如,要將所有段落標籤在DIV中獲取類“ content”:soup.select("div.content p")
。 span
如果數據在具有獨特屬性的標籤中,請直接定位它們。例如,如果一個價格是在帶有id="price"
屬性的A soup.find('span', id='price').text
標籤中,請使用.find_next_sibling()
瀏覽樹:.find_parent()
使用re.findall()
正則表達式:對於復雜的方案或非結構化數據,將美麗的湯與正則表達式相結合以根據文本中的模式將數據結合起來,以提取數據。 在使用美麗的湯中提取相關文本後,請使用find_all()
使用帶有soup.find_all(lambda tag: tag.name == 'p' and 'price' in tag.text)
的lambda函數來根據特定標準過濾結果。這有助於根據屬性值或文本內容選擇標籤。 示例:以上是Python Beautifulsoup示例備忘單的詳細內容。更多資訊請關注PHP中文網其他相關文章!