BeautifulSoup 网页作者与单位信息精准提取教程
技术百科
花韻仙語
发布时间:2026-01-27
浏览: 次 本文详解如何使用 beautifulsoup 高效、鲁棒地提取科研文章中作者名与所属单位(affiliation)信息,解决嵌套结构遍历、缺失数据处理及 class 定位失效等常见爬虫难题。
在网页结构化数据抓取中,作者与单位信息常以 和 形式成对或非严格邻接出现。初学者易陷入“暴力遍历所有 ”的误区(如第一段代码),导致 find() 返回 None——根本原因在于:未限定搜索范围,目标元素被大量无关 干扰,且 tar.find(...) 在错误上下文中执行。
正确做法是先定位语义容器,再精准提取。观察目标页面(如 https://rpmgf.pt/.../13494),作者区块实际包裹在
from bs4 import BeautifulSoup, SoupStrainer
import requests
# 仅解析作者区块,跳过整个 DOM 解析
STRAINER = SoupStrainer(name='section', class_='item authors')
def get_author_data(article_id: int) -> list[tuple[str, str | None]]:
url = f"https://rpmgf.pt/ojs/index.php/rpmgf/article/view/{article_id}"
with requests.get(url) as r:
r.raise_for_status()
# 使用 parse_only 显著加速解析
soup = BeautifulSoup(r.
text, 'lxml', parse_only=STRAINER)
authors = []
for name_tag in soup.find_all('span', class_='name'):
name = name_tag.get_text(strip=True)
# 在 name_tag 后续兄弟节点中查找最近的 affiliation
affiliation = None
for sibling in name_tag.next_siblings:
if sibling.name == 'span' and 'affiliation' in (sibling.get('class') or []):
affiliation = sibling.get_text(strip=True)
break
elif sibling.name == 'span' and 'name' in (sibling.get('class') or []):
# 遇到下一个作者,说明当前作者无 affiliation
break
authors.append((name, affiliation))
return authors
# 使用示例
for name, aff in get_author_data(13494):
print(f"{name} → {aff or '[无单位]'}")✅ 关键优化点说明:SoupStrainer 过滤无效 HTML,避免内存浪费与误匹配;next_siblings 替代全局 find_all('span', class_='affiliation'),确保 affiliation 与 author 的逻辑归属关系;对 class_ 属性使用 in (sibling.get('class') or []) 安全判断,兼容 class=None 或空列表;get_text(strip=True) 自动清理换行符与多余空格,无需额外 strip()。
对于“部分作者缺失 affiliation”的边界情况(如 article 13545),上述逻辑通过 break 提前终止搜索,并自然赋值 None,完全规避 zip() 导致的长度不匹配错误。若需导出 CSV,可安全写入:
import csv
with open("authors.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Author", "Affiliation"])
for name, aff in get_author_data(13494):
writer.writerow([name, aff or ""])总结:BeautifulSoup 抓取的核心不是“找所有标签”,而是“理解 DOM 结构层级”。始终遵循「容器定位 → 子元素遍历 → 邻近关系验证」三步法,配合 SoupStrainer 和 next_siblings 等精准 API,即可稳健应对复杂学术网页的作者信息提取任务。
# ai
# 结构化
# 爬虫
# 数据处理
# 跳过
# 若需
# app
# https
# js
# class
# html
# 根本原因
# php
# break
# 遍历
# csv
# dom
# 如何使用
# 不匹配
# elif
# 常以
# 或非
# beautifulsoup
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- 如何在Golang中处理URL参数_Golang
- 如何在Golang中定义接口_抽象方法和多态实现
- C#怎么创建控制台应用 C# Console Ap
- Linux如何申请SSL免费证书_Linux下Ce
- Win11如何更改任务栏颜色 Win11自定义任务
- Win11输入法切换快捷键怎么改_Windows
- 如何在 Go 中调用动态链接库(.so)中的函数
- Windows如何使用注册表查找和删除项?(reg
- Mac版Final Cut Pro入门_Mac视频
- php8.4新语法match怎么用_php8.4m
- LINUX怎么查看进程_LINUX ps命令查看运
- php嵌入式多设备通信怎么实现_php同时管理多个
- Win11怎么开启远程桌面连接_Windows11
- 微信短链接怎么还原php_用浏览器开发者工具抓包获
- php485读数据时阻塞怎么办_php485非阻塞
- c# Task.Yield 的作用是什么 它和Ta
- Win11怎么关闭应用权限_Windows11相机
- 如何使用正则表达式提取以编号开头、后接多个注解的逻
- Win11怎么关闭贴靠布局_Win11禁用窗口最大
- Python迭代器生成器进阶教程_节省内存与懒加载
- Win10如何优化内存使用_Win10内存优化技巧
- Windows10电脑怎么设置虚拟光驱_Win10
- Win11怎么设置虚拟键盘_打开Win11屏幕键盘
- Win11时间格式怎么改成12小时制 Win11时
- 用Python构建微服务架构实践_FastAPI与
- PHP 中如何在函数内持久化修改引用变量的指向
- 如何使用Golang benchmark测量函数延
- VSC怎么创建PHP项目_从零开始搭建项目的步骤【
- Windows10怎样设置家长控制_Windows
- php485能和物联网模块通信吗_php485对接
- Win11怎么开启上帝模式_创建Windows 1
- Win11怎么设置默认邮件应用_Windows11
- PHP主流架构怎么处理表单验证_规则与自定义【技巧
- LINUX的SELinux是什么_详解LINUX强
- php接口返回数据乱码怎么办_php接口调试编码问
- 如何在Golang中指定模块版本_使用go.mod
- Win11怎么设置声音输出设备_Windows11
- Python字符串操作教程_切片拼接与格式化详解
- php内存溢出怎么排查_php内存限制调试与优化方
- php能跑在stm32上吗_php在stm32微控
- php会话怎么开启_session_start函数
- 如何在Golang中实现服务熔断与限流_Golan
- c++输入输出流 c++ cin与cout格式化输
- c++ std::atomic如何保证原子性 c+
- PHP怎么接收前端传的时间戳_处理时间戳参数转换技
- Python项目回滚策略_发布安全说明【指导】
- PHP主流架构怎么集成Redis缓存_配置步骤【方
- php后缀怎么变mp4能播放_让php伪装mp4正
- Win11关机快捷键是什么_Win11快速关机方法
- Win11怎么关闭自动维护 Win11禁用系统自动


QQ客服