使用BeautifulSoup提取网页type字段输出为空 该如何正确处理
错误原因
- HTML规范中
id属性是全局唯一的,你在每个class="paper"的子节点下查找id="info"的div,但id="info"的节点不属于paper节点的子元素,在循环内查找自然返回空。 - 就算定位到了
id="info"的节点,你也没有进一步提取内部<strong>标签对应的type字段内容,无法得到目标文本。 - 循环变量用了Python内置关键字
property,容易引发命名冲突,建议更换。
解决代码
如果要提取页面全局的type字段,直接全局定位即可,不需要放在paper遍历的循环内:
from bs4 import BeautifulSoup import requests url='https://ash.confex.com/ash/2021/webprogram/Session20851.html' res = requests.get(url) res.encoding = res.apparent_encoding # 避免编码乱码 soup = BeautifulSoup(res.text, 'html.parser') # 全局定位info节点 info_node = soup.find("div",{"id":"info"}) # 提取内部strong标签中对应type的内容 type_ = info_node.find("strong", string="Type:").next_sibling.strip() print(type_) # 遍历每个paper的相关字段,更换了循环变量名 content = soup.find_all('div', class_='paper') for item in content: title = item.find('div',class_='cricon').text.strip() print(title)
补充说明
如果你的需求是提取每个paper条目对应的类型,只需要调整查找逻辑,在paper节点内定位对应的类型标签即可,不需要找全局的id="info"节点。
内容的提问来源于stack exchange,提问作者Void S
相关产品推荐
相关产品推荐

