【问题标题】:How do I get data from a div in python?如何从 python 中的 div 获取数据?
【发布时间】:2022-01-23 07:45:22
【问题描述】:

我正在编写一个应该从 div 返回文本的 python 脚本。 html 看起来像这样:

<div id="bodyContent" class="vector-body">
    <div id="siteSub" class="noprint">From Wikipedia, the free encyclopedia</div>

所以我的脚本应该返回:“来自维基百科,免费的百科全书”,但它什么也没返回

source = requests.get("https://en.wikipedia.org/wiki/2021_Osaka_building_fire").text

soup = BeautifulSoup(source, 'lxml')

print(soup.select_one("div[class*=noprint]").text)

我做错了什么?

【问题讨论】:

  • class*=noprint 星号的用途是什么?
  • 如果你使用soup.select('div', {'class': 'noprint'})之类的东西,你会发现这是第7个匹配的div有你需要的文本,select_one给你第一个,这确实是空的。跨度>

标签: python web-scraping beautifulsoup


【解决方案1】:

问题是页面中还有其他 div.noprint,它捕获的“一个”是空的

另一种方法是通过 id 找出:

print(soup.select_one("div[id*=siteSub]").text)

【讨论】:

    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多