首页 > 解决方案 > 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'] 的列表,而不是文章的正文。我到底哪里错了?

标签: pythonhtmlweb-scrapingtags

解决方案


我会在 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 或条件逻辑处理的文本。


推荐阅读