【问题标题】:How to get 2 different classes text in a div如何在 div 中获取 2 个不同的类文本
【发布时间】:2019-11-03 13:42:34
【问题描述】:

我正在尝试使用 Python 和 BeautifulSoup 进行网络抓取,但我碰壁了。这是原始页面标记:

 <div class="name">target 1<div class="date">updated 25th January 2019</div></div>

我只需要第一部分(“目标 1”)

我试图用

找到类“名称”
mgroup[0].a.findAll("div",{"class":"name"})

mgroup[0].a.findAll("div",)[1].div 

但它总是返回

<div class="name">target 1<div class="date">updated 25th January 2019</div></div>

但是如果我像这样使用“日期”类

mgroup[0].a.findAll("div",{"class":{"date"})

我明白了:

<div class="date">updated 25th January 2019</div>

我不确定这是因为 div 位于未封闭的 div 内,还是标签“名称”可能是保留术语或类似的东西,甚至尝试过

mgroup[0].a.findAll("div",{"class":["name"}])

结果相同

  [<div class="name">target 1<div class="date">updated 25th January 2019</div></div>]

我应该如何解决这个问题?

【问题讨论】:

    标签: web-scraping beautifulsoup


    【解决方案1】:

    它返回 BS4 元素本身。您可以像这样访问元素的内容:

    hit = mgroup[0].a.findAll("div",{"class":"name"})
    print(hit.contents[0])
    

    【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2016-11-13
    • 1970-01-01
    相关资源
    最近更新 更多