Python HTML scraping找不到我知道存在的属性?

2024-09-25 16:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用lxml和requests模块,并尝试解析来自新闻网站的文章,下面是一篇示例文章的链接:https://www.thehindu.com/news/national/karnataka/kumaraswamy-congress-leaders-meet-to-discuss-cabinet-reshuffle/article27283040.ece

如果检查文章的主体,可以看到它位于名为“article”的div类中。我试图用这个类来解析这篇文章,但我总是空出来。没有错误什么的,就是找不到

我也试着用了从BeautifulSoup找到所有的东西,但结果还是空的

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','\n']的列表,而不是文章的正文。我到底错在哪里


Tags: httpscomwwwarticle文章requestslxmlnews
1条回答
网友
1楼 · 发布于 2024-09-25 16:28:11

我将在cssselect_one中使用bs4和类名

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或条件逻辑处理这些文本

相关问题 更多 >