Python bs4 解析不对, 更新bs4 库 或 单独调用 Scrapy 的 css 选择器

本文介绍了解决bs4解析特定CSS选择器失败的问题,通过升级bs4库至4.7.0以上版本,并使用Scrapy的css选择器替代,成功解析了如'div.show-status>span:nth-child(3)'等规则。

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

更新bs4库至4.7.0以上,然后就可以使用了。(推荐)

pip install --upgrade beautifulsoup4

比如这个规则,bs4 解析不出来, 会报错 需要将nth-child改为 nth-of-type,

虽然这样不会报错了,但是解析的位置不对

div.show-status > span:nth-child(3)

 

解决方法:

调用Scrapy 的 css 选择器

import requests
from scrapy.selector import Selector

url = 'http://www.tchuan.gov.cn/show/2019/03/07/36310.html'


# ['h1.show-title', 'div.show-status > span:nth-child(3)', '#content']
html = requests.get(url)
a = Selector(text = html.text)
b = a.css('div.show-status > span:nth-child(3)').extract()[0]

print(a)
print(b)

 

### 使用CSS选择器Python网络爬虫中的应用 对于希望利用CSS选择器简化网页元素定位过程的开发者而言,在Python中存在多种实现方式。BeautifulSoup和Scrapy均支持通过CSS选择器选取HTML文档内的特定部分。 #### 在BeautifulSoup中使用CSS选择器 当采用`BeautifulSoup`处理HTML内容时,除了能够运用XPath表达式外,也完全兼容CSS选择器语法。下面展示了一个简单的实例: ```python from bs4 import BeautifulSoup html_doc = """ <html> <head><title>Example</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> """ soup = BeautifulSoup(html_doc, 'html.parser') # Select all elements with "sister" class using CSS selector syntax. links = soup.select(".sister") for link in links: print(link.get_text()) ``` 此代码片段展示了如何借助`.select()`方法并传入相应的CSS类名来获取具有`sister`类的所有标签[^1]。 #### 在Scrapy中使用CSS选择器 同样地,在Scrapy框架下也可以方便地调用CSS选择器来进行数据提取操作。这里给出一段基于Scrapy Spider的例子: ```python import scrapy class ExampleSpider(scrapy.Spider): name = "example" start_urls = [ 'https://www.example.com/', ] def parse(self, response): # Extract text inside <h1> tag by CSS Selector title = response.css('h1::text').get() yield { 'page_title': title, } ``` 上述例子说明了怎样定义一个名为`parse`的方法用于解析响应对象,并从中抽取指定样式的选择器所匹配的内容[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值