You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:BeautifulSoup select_one无法找到指定标签的问题求助

问题解决方法

你的问题出在子选择器>的使用限制上:你写的选择器最后用了>,这要求div.content_s必须是div.wrap_content_view的直接子元素(也就是中间不能有其他嵌套标签),但实际通过requests获取的原始HTML里,这两个标签之间存在其他嵌套元素,所以子选择器无法匹配到目标元素。

两种可行的解决办法:

  1. 改用后代选择器:把最后的>换成空格,这样可以匹配所有嵌套在div.wrap_content_view内部的div.content_s元素,不管它是不是直接子元素:
import requests
from bs4 import BeautifulSoup

url = 'http://ch1.skbroadband.com/content/view?parent_no=24&content_no=57&p_no=154494'

web = requests.get(url,headers={'User-Agent':'Mozilla/5.0'})
source = BeautifulSoup(web.text,'html.parser')

# 把最后的>换成空格,改为后代选择器
source = source.select_one('body > div.wrapper > div.container > div.contentBox > div > div.wrap_content_view div.content_s')

print(source)
  1. 简化选择器:既然页面中只有一个content_s类的元素,直接使用类选择器即可,无需写冗长的完整路径,代码更简洁且不易出错:
import requests
from bs4 import BeautifulSoup

url = 'http://ch1.skbroadband.com/content/view?parent_no=24&content_no=57&p_no=154494'

web = requests.get(url,headers={'User-Agent':'Mozilla/5.0'})
source = BeautifulSoup(web.text,'html.parser')

# 直接使用类选择器
source = source.select_one('.content_s')

print(source)

你可以通过打印div.wrap_content_view的HTML内容,确认div.content_s的实际嵌套结构——大概率是中间存在其他标签,导致子选择器无法匹配。

内容的提问来源于stack exchange,提问作者mmd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:13:13