Python中如何获取网页标签?
使用 bs4 可以很轻松获得网页文字内容,但是如果想获得网页的标签信息应该怎么做?
假如网页源码是
<html>
<head>
<title>The Dormouse’s story</title>
</head>
<body>
<p class=“title”><b>The Dormouse’s story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p>
<p class="story">...</p>
</body>
</html>
获得网页标签结构
<html>
<head>
<title> </title>
</head>
<body>
<p class=“title”><b> </b></p>
<p class="story">
<a href="http://example.com/elsie" class="sister" id="link1"> </a>
<a href="http://example.com/lacie" class="sister" id="link2"> </a>
<a href="http://example.com/tillie" class="sister" id="link3"> </a> </p>
<p class="story"> </p>
</body>
</html>
Python中如何获取网页标签?
用Python获取网页标签,最直接的方法是BeautifulSoup。先装库:pip install beautifulsoup4 requests。
核心就两步:1. 用requests拿到网页HTML;2. 用BeautifulSoup解析并提取标签。
看个具体例子,假设我们要抓取某个网页里所有的<a>链接:
import requests
from bs4 import BeautifulSoup
# 1. 获取网页内容
url = 'https://example.com'
response = requests.get(url)
html_content = response.text
# 2. 解析HTML
soup = BeautifulSoup(html_content, 'html.parser')
# 3. 查找所有<a>标签
links = soup.find_all('a')
# 4. 提取href属性
for link in links:
href = link.get('href')
text = link.text.strip()
if href: # 只打印有链接的
print(f"链接文本: {text}, 地址: {href}")
关键点解析:
soup.find_all('a'):返回所有<a>标签的列表。想找其他标签,比如<div>,就把'a'换成'div'。link.get('href'):获取标签的href属性值。其他属性比如class、id也一样用.get('属性名')。link.text:获取标签内的文本内容,.strip()去掉首尾空白。
如果你想通过CSS类名来精确定位,比如找所有class="menu-item"的<div>:
items = soup.find_all('div', class_='menu-item')
注意参数是class_(带下划线),因为class是Python关键字。
如果只要第一个匹配的标签,用find()代替find_all():
first_link = soup.find('a')
简单说,BeautifulSoup让解析HTML像查字典一样简单。
你是不是想要这些内容。
我是熬两次汤,熬出来的。不知道其他人有没有其他好用的方法。
官方教程的快速开始有这个 get()方法
from bs4 import BeautifulSoup
>>> html = “”"<html> … </html>"""
>>> soup = BeautifulSoup(html, “html.parser”)
>>> ssoup = BeautifulSoup(str(soup.find_all(attrs={‘class’:‘story’})), “html.parser”)
>>> ssoup.find_all(‘a’)[0].get(‘href’)
‘http://example.com/elsie’
>>>

