首先安装它。 我们将使用一个简单的示例html smippet:pip install beautifulsoup4
<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>
>导入beautifutsoup:
from bs4 import BeautifulSoup
>
html = """<html>...</html>""" # Your HTML string goes here. soup = BeautifulSoup(html, 'html.parser')
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中文网其他相关文章!