Python 使用 BeautifulSoup bs4 时 nth-child(6) 报错:

在使用 BeautifulSoup 的过程中遇到 'nth-child' 报错,错误信息提示仅实现了 'nth-of-type'。解决方案是将 nth-child 替换为 nth-of-type。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错:

'Only the following pseudo-classes are implemented: nth-of-type.')
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
 

解决办法:

nth-child 改为 nth-of-type 

from bs4 import BeautifulSoup as bs


a = '''
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="keywords" content="内乡宝天曼峡谷漂流景区开漂公告,内乡县政府,内乡县人民政府">
	<meta name="description" content="内乡县位于河南省西南部,南阳盆地西缘。东接镇平,南连邓州,西邻淅川、西峡,北依嵩县、南召。地形呈南北条状,南北长85公里,东西宽54公里,总面积2465平 方公里,耕地面积76万亩。全县辖16个乡镇289个行政村和8个居民委员会,3840个村民小组,总人口63万人。">
	<title>内乡宝天曼峡谷漂流景区开漂公告-内乡县人民政府</title>
	<link rel="stylesheet" type="text/css" href="http://static.neixiangxian.gov.cn/css/reset.css"/>
	<link rel="stylesheet" type="text/css" href="http://static.neixiangxian.gov.cn/css/detail.css"/>
	<script src="http://static.neixiangxian.gov.cn/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	<style>
		#my-video{
			height: auto !important;
		}
		.my-player .my-video-dimensions{
			height: auto !important;
		}
	</style>
</head>
<body>
<!--header开始-->
<script src="http://static.neixiangxian.gov.cn/js/top.js"></script>
<!--header开始-->
<div class="wrapper">
	<div class="width1000 containBox">
		<P class="detailTitle">首页  > 公示公告</P>
		<div class="conBox clearfix">
			<h1 class="title">内乡宝天曼峡谷漂流景区开漂公告</h1>
			<p class="detailTxt">
				<a href="/">内乡政府门户网站&nbsp www.neixiangxian.gov.cn</a>
				&nbsp&nbsp<span>2018-04-19 17:32:17</span>&nbsp&nbsp
				<span>来源:内乡县政府网站</span>
			</p>
			<div class="contentBox">
				<p class="MsoNormal" style="text-indent:32.1500pt;mso-char-indent-count:2.0000;"><img src="http://file.neixiangxian.gov.cn/attached/20180419/20180419173149_594.jpg" alt="8E6ABF5A@A5E2F63D" style="max-width:100%;"></p><p class="MsoNormal" style="text-indent:32.1500pt;mso-char-indent-count:2.0000;"><b><span style="font-family: 宋体; font-size: 16pt;"><font face="宋体">内乡宝天曼峡谷漂流兹定于</font>2018<font face="宋体">年</font><font face="Calibri">5</font><font face="宋体">月</font><font face="Calibri">1</font><font face="宋体">日正式对外开漂运营,热诚欢迎社会各界新老朋友前来激情漂流,体验大自然赋予的鬼斧神工,也给您炎热夏季开一个好兆头。给您一天时间,让你重返快乐童年!</font></span></b></p><p class="MsoNormal" style="text-indent:32.1500pt;mso-char-indent-count:2.0000;"><b><span style="font-family: 宋体; font-size: 16pt;"><font face="宋体">详情请咨询:</font>13733127888 &nbsp;&nbsp;&nbsp;0377<font face="宋体">—</font><font face="Calibri">65157888</font></span></b></p><p class="MsoNormal" style="text-indent:32.1500pt;mso-char-indent-count:2.0000;"><b style="text-indent: 16.05pt;"><span style="font-family: 宋体; font-size: 16pt;">特此公告!</span></b></p><p class="MsoNormal"><b><span style="font-family: 宋体; font-size: 16pt;">&nbsp;</span></b></p><p class="MsoNormal"><b><span style="font-family: 宋体; font-size: 16pt;">&nbsp;</span></b></p><p class="MsoNormal" align="right" style="text-align:right;"><b><span style="font-family: 宋体; font-size: 16pt;">内乡宝天曼峡谷漂流有限公司</span></b><b><span style="font-family: 宋体; font-size: 16pt;"><o:p></o:p></span></b></p><p class="MsoNormal" align="right" style="margin-right:16.0000pt;text-align:right;"><b><span style="font-family: 宋体; font-size: 16pt;">二〇一八年四月十九日</span></b><b><span style="font-family: 宋体; font-size: 16pt;"><o:p></o:p></span></b></p><p><br></p> 
			</div>
			<P class="zrEditor">责任编辑:管理员</P>
			<div class="clearfix sharebox fr">
				<span class="fl">分享:</span>
				<div class="bdsharebuttonbox fl">
					<a href="#" class="bds_more" data-cmd="more"></a>
					<a href="#" target='_blank' class="bds_qzone bdkj" data-cmd="qzone" title="分享到QQ空间"></a>
					<a href="#" target='_blank' class="bds_weixin bdwx" data-cmd="weixin" title="分享到微信"></a>
					<a href="#" target='_blank' class="bds_tsina bdwb" data-cmd="tsina" title="分享到新浪微博"></a>
					<a href="#" target='_blank' class="bds_sqq bdqq" data-cmd="sqq" title="分享到QQ好友"></a>
				</div>
				<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://static.neixiangxian.gov.cn/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
			</div>
		</div>
	</div>
</div>
<!--footer开始-->
<script src="http://static.neixiangxian.gov.cn/js/footer.js"></script>
<!--footer结束-->
<script src="http://static.neixiangxian.gov.cn/js/common.js"></script>
<script src="http://static.neixiangxian.gov.cn/static/api/js/share.js?v=89860593.js?cdnversion=417672"></script>
</body>
</html>
'''


soup = bs(a,'lxml')
b = soup.select('span:nth-of-type(2)')
print(b)

 

<think>好的,用户想要了解BeautifulSoup4库的使用示例和代码教程。首先,我需要整理之前提供的引用内容,看看有哪些相关的信息可以利用。根据引用[1],BeautifulSoup4主要用于解析HTML和XML,提取数据,并且有find、find_all等方法。引用[2]提到了安装方法,需要安装requests和beautifulsoup4库。引用[3]讨论了不同的解析器,比如Python标准库的html.parser,还有lxml等。引用[4]强调了BeautifulSoup的简单性和编码处理能力。引用[5]给了一个实际案例的URL,中国天气网站,可以用来作为示例。 首先,用户可能需要一个完整的代码示例,从安装到实际应用。所以第一步应该是安装步骤,引用[2]提到了安装命令,可以写出来。然后,需要导入必要的库,比如requests和BeautifulSoup。接下来,选择一个目标网站,这里可以用引用[5]中的中国天气网站作为例子,华北地区的页面。然后发送HTTP请求获取页面内容,处理可能的编码问题,引用[4]提到自动处理编码,但可能需要手动指定,如果遇到问题的话。 接下来是解析HTML内容,根据引用[3],可以选择html.parser或者lxml。这里可能用html.parser作为示例,因为它是内置的,不需要额外安装。然后使用BeautifulSoup的方法,比如find和find_all,或者CSS选择器来提取数据。例如,找到特定的div或者类,提取城市名称和温度等信息。 在代码示例中,需要展示如何定位元素,遍历结果,并提取所需的数据。同,要处理可能出现的异常,比如网络请求失败,或者元素不存在的情况。不过为了示例简洁,可能暂不加入异常处理,但最好在教程中提到这一点。 另外,引用[1]中的常用属性和方法,比如soup.title、soup.get_text(),也可以在示例中展示。例如,打印页面标题,或者提取所有文本内容。但用户可能更关注结构化的数据提取,比如表格或列表中的信息。 最后,生成相关问题,可能涉及性能优化、不同解析器的比较、处理动态网页等,这些问题可以帮助用户进一步学习。需要确保问题与内容相关,并且基于提供的引用材料。 现在需要组织这些思路,写出结构清晰的步骤,包含安装、导入库、发送请求、创建BeautifulSoup对象、使用方法和属性、提取数据的具体例子,以及总结和问题。同,注意使用正确的LaTeX格式,但在这个问题中可能涉及较少数学公式,不过代码块需要正确标记。检查引用标记是否正确添加在相关说明的末尾,比如安装步骤引用[2],解析器部分引用[3]等。</think>### Python BeautifulSoup4 使用示例与教程 #### 1. 安装依赖库 安装所需库(引用[2]): ```bash pip install requests beautifulsoup4 ``` #### 2. 基础使用步骤 ##### 2.1 导入库 ```python import requests from bs4 import BeautifulSoup ``` ##### 2.2 发送请求获取页面 以中国天气网华北地区页面为例(引用[5]): ```python url = "http://www.weather.com.cn/textFC/hb.shtml" response = requests.get(url) response.encoding = "utf-8" # 手动指定编码(引用[4]) html_content = response.text ``` ##### 2.3 创建BeautifulSoup对象 使用`html.parser`解析器(引用[3]): ```python soup = BeautifulSoup(html_content, "html.parser") ``` ##### 2.4 常用方法示例 **提取页面标题**: ```python print("页面标题:", soup.title.string) ``` **查找所有城市名称与温度**(引用[1]): ```python # 查找包含天气信息的<div>标签 weather_divs = soup.find_all("div", class_="conMidtab")[0] # 遍历每个城市信息行 for table in weather_divs.find_all("table"): for row in table.find_all("tr")[2:]: # 跳过表头 city = row.find("a").text temp = row.find_all("td")[-2].text print(f"城市: {city}, 最低温度: {temp}") ``` #### 3. 完整代码示例 ```python import requests from bs4 import BeautifulSoup url = "http://www.weather.com.cn/textFC/hb.shtml" response = requests.get(url) response.encoding = "utf-8" soup = BeautifulSoup(response.text, "html.parser") # 提取华北地区城市天气 weather_data = [] for table in soup.select("div.conMidtab table"): for row in table.find_all("tr")[2:]: city = row.find("a").text.strip() temp = row.select("td:nth-last-child(2)")[0].text.strip() weather_data.append({"城市": city, "温度": temp}) print("华北地区天气数据:") for item in weather_data[:5]: # 展示前5条结果 print(item) ``` #### 4. 关键方法说明 - **`find()`**: 返回第一个匹配的标签(引用[1]) - **`find_all()`**: 返回所有匹配标签的列表 - **CSS选择器**: 使用`select()`方法更灵活定位元素 - **编码处理**: 自动处理Unicode与UTF-8(引用[4])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值