python - 如何在 Python 中使用 BeautifulSoup 从文本中获取标签
问题描述
我想从文本中获取标签和类名。
示例 HTML:
<a _sp="p2481888.m1379.l3250" href="https://www.ebay.com/b/Electronics/bn_7000259124">Electronics</a>
如何获取标签和类名?a
和p2481888.m1379.l3250
from bs4 import BeautifulSoup
import requests
Source = input("Enter the source: ")
Request = requests.get(Source, headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59"})
Soup = BeautifulSoup(Request.text, "html.parser")
Target = Soup.find_all(text="Electronics")
print(Target)
这是一张图片:
解决方案
当您这样做时,它会根据您的情况find_all(text="Electronics")
返回文本Electronics
。要获取a
,您可以使用.previous_element
,然后,要获取标签的名称,请使用.name
。文本p2481888.m1379.l3250
是标签的属性,使用以下方式访问它[]
:
from bs4 import BeautifulSoup
html = """<a _sp="p2481888.m1379.l3250" href="https://www.ebay.com/b/Electronics/bn_7000259124">Electronics</a>"""
soup = BeautifulSoup(html, "html.parser")
target = soup.find_all(text="Electronics")
for tag in target:
a_tag = tag.previous_element
print("Tag name:", a_tag.name)
print(a_tag["_sp"])
输出:
Tag name: a
p2481888.m1379.l3250
或者,您可以将标签的名称直接传递给find_all()
:
target = soup.find_all("a", text="Electronics")
for tag in target:
print("Tag name:", tag.name)
print(tag["_sp"])
推荐阅读
- excel - 如何在 Excel 数据透视图中绘制 90000 个点
- javascript - 如何减少我的 vuejs 网络应用程序的 app.js 大小?
- cgal - 查找源面和目标面之间的所有面
- php - Laravel 广播身份验证工作或用于网络保护或自定义保护
- node.js - (节点:3966)UnhandledPromiseRejectionWarning:错误:querySrv ECONNREFUSED
- json - 如何使用 jq 将项目映射到 json 结构中?
- azure-ad-b2c - 响应 Blazor Web Assembly 应用程序和 Azure AD B2C 登录成功
- typescript - 如何在 TypeScript 中动态设置 MaterialUI 网格大小道具的值?
- python - 如何获取由 subprocess.run 启动的进程的 pid 并杀死它
- salesforce - “更新插入的字段无效,必须是外部 ID 自定义或标准索引字段:名称”错误