如何在Beautiful Soup网页抓取过程中获取post id
提取post id的实现方法
soup.find("article") 返回的是BeautifulSoup的Tag对象,你可以直接读取该对象的属性值拿到id:
- 基础写法(如果确定页面一定有article标签且带id属性):
post_id = soup.find("article")["id"] # 得到的结果为 post-518551
- 容错写法(避免标签不存在时报错中断程序):
article_tag = soup.find("article") post_id = article_tag.get("id") if article_tag else None
如果你只需要id里的数字部分当文件名,可以再做字符串分割:
if post_id: file_name = post_id.split("-")[-1] + ".txt"
额外优化建议
你当前使用固定索引定位元素的写法(比如 find_all('h1')[1]、find_all("span")[39])稳定性较差,网页结构微调就会失效,建议结合标签的class属性定位:
- 标题:
title = soup.find("h1", class_="title").text - 副标题:
subtitle = soup.find("h2", class_="description").text - 日期可以找对应span的class属性做定位,适配性会高很多。
内容的提问来源于stack exchange,提问作者Guilherme Giuliano Nicolau
相关产品推荐
相关产品推荐

