【问题标题】:BS4 returns [] instead of the wanted HTML tagBS4 返回 [] 而不是想要的 HTML 标签
【发布时间】:2020-11-15 13:40:28
【问题描述】:

我想解析给定的网站并抓取表格。对我来说,代码看起来是正确的。 Python 和 Web 解析新手

import requests
from bs4 import BeautifulSoup
response = requests.get('https://delhifightscorona.in/')
doc = BeautifulSoup(response.text, 'lxml-xml')

cases = doc.find_all('div', {"class": "cell"})

print(cases)

这样做会返回

[]

【问题讨论】:

  • 您到底想要什么信息?页面上没有名为celldiv
  • 感谢您的回复!我想打印案例总数。我想按类解析,很新我犯了一个错误

标签: python html parsing beautifulsoup


【解决方案1】:

更改您的解析器和类,就可以了。

import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('https://delhifightscorona.in/').text, 'html.parser').find('div', {"class": "grid-x grid-padding-x small-up-2"})

print(soup.find("h3").getText())

输出:

423,831

【讨论】:

    【解决方案2】:

    您可以选择仅打印案例或带有日期的总统计数据。

    import requests
    from bs4 import BeautifulSoup
    response = requests.get('https://delhifightscorona.in/')
    doc = BeautifulSoup(response.text, 'html.parser')
    stats = doc.find('div', {"class": "cell medium-5"})
    print(stats.text)                 #Print the whole block with dates and the figures
    cases = stats.find('h3')
    print(cases.text)         #Print the cases only
    

    【讨论】:

    • 谢谢!!这正是我想要的
    • 完成。我们需要等待至少 2 分钟才能标记正确答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多