如何用css提取标题?
试过#wrapper #content h1:: text无法提取出“肖申克救赎”,且返回的是空白
该回答引用ChatGPT
在 Python 中使用 CSS 提取文本需要借助第三方库,比如 BeautifulSoup。下面是一个示例代码,假设要从 HTML 中提取
from bs4 import BeautifulSoup
import requests
# 发送请求,获取 HTML 内容
response = requests.get('http://example.com')
html = response.content
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 提取 <h1> 标签的文本
h1_text = soup.select_one('h1').text
print(h1_text)
这段代码使用 requests 库向指定的 URL 发送请求,获取 HTML 内容。然后使用 BeautifulSoup 解析 HTML,soup.select_one('h1') 返回第一个
需要注意的是,CSS 选择器中的空格 表示嵌套关系,比如 #wrapper #content h1 表示 id="wrapper" 的元素下,id="content" 的元素下,