python - Python HTML抓取找不到我知道存在的属性?
问题描述
我正在使用 lxml 和 requests 模块,只是试图从网站解析文章。我尝试使用 BeautifulSoup 中的 find_all 但仍然是空的
from lxml import html
import requests
page = requests.get('https://www.thehindu.com/news/national/karnataka/kumaraswamy-congress-leaders-meet-to-discuss-cabinet-reshuffle/article27283040.ece')
tree = html.fromstring(page.content)
article = tree.xpath('//div[@class="article"]/text()')
打印文章后,我会得到 ['\n','\n','\n','\n','\n'] 的列表,而不是文章的正文。我到底哪里错了?
解决方案
我会在 css 中使用 bs4 和类名select_one
import requests
from bs4 import BeautifulSoup as bs
page = requests.get('https://www.thehindu.com/news/national/karnataka/kumaraswamy-congress-leaders-meet-to-discuss-cabinet-reshuffle/article27283040.ece')
soup = bs(page.content, 'lxml')
print(soup.select_one('.article').text)
如果你使用
article = tree.xpath('//div[@class="article"]//text()')
你得到一个列表,仍然得到所有的 \n 以及我认为你可以用 re.sub 或条件逻辑处理的文本。
推荐阅读
- java - 如何使用 java sdk 在 Azure Blob 存储中上传单个视频文件的多个块?
- c++ - 使用 std::basic_ifstream 的文件 I/O
- c# - 对蛇游戏进行单元测试
- magento - Magento 2.4 CE 是否有本地客户信用模块?
- kubernetes - 在 IBM 云上运行 Openshift API 的身份验证失败,出现 401 未经授权的错误
- java - 如何通过 web3j 从 geth 获取 txpool 中的待处理 txns 和排队 txns
- google-sheets - ArrayFormula 与电子表格中的平均公式
- mathjax - MathJax 3:\text{} 和 \textrm{} 之间有什么区别吗?
- android - 如何获得 ios 和 android 的活动推荐(在 react native 项目中)
- ffmpeg - ffmpeg 管道从 numpy 数组或 bgr24 字节生成 h264 块