【问题标题】:Python HTML scraping cannot find attribute I know exists?Python HTML 抓取找不到我知道存在的属性?
【发布时间】:2019-10-14 20:31:02
【问题描述】:

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

【问题讨论】:

    标签: python html web-scraping tags


    【解决方案1】:

    我会使用 bs4 和 css 中的类名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 或条件逻辑处理的文本。

    【讨论】:

    • 是的,这确实有效,现在我只选择了文章类。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多