【问题标题】:Python Beautiful Soup Extracting HTML Meta DataPython Beautiful Soup 提取 HTML 元数据
【发布时间】:2018-05-30 20:18:30
【问题描述】:

我遇到了一些我不太理解的奇怪行为。我希望有人能解释发生了什么。

考虑这个元数据:

<meta property="og:title" content="This is the Tesla Semi truck">
<meta name="twitter:title" content="This is the Tesla Semi truck">

此行成功找到所有“og”属性并返回一个列表。

opengraphs = doc.html.head.findAll(property=re.compile(r'^og'))

但是,这条线无法为 twitter 卡做同样的事情。

twitterCards = doc.html.head.findAll(name=re.compile(r'^twitter'))

为什么第一行成功找到了所有的“og”(opengraph 卡片),却没有找到twitter 卡片?

【问题讨论】:

    标签: python html twitter web-scraping beautifulsoup


    【解决方案1】:

    问题是name=,它有特殊含义。它用于查找标签名称 - 在您的代码中它是 meta

    您必须添加"meta" 并将字典与"name" 一起使用

    不同项目的示例。

    from bs4 import BeautifulSoup
    import re
    
    data='''
    <meta property="og:title" content="This is the Tesla Semi truck">
    <meta property="twitter:title" content="This is the Tesla Semi truck">
    <meta name="twitter:title" content="This is the Tesla Semi truck">
    '''
    
    head = BeautifulSoup(data)
    
    print(head.findAll(property=re.compile(r'^og'))) # OK
    print(head.findAll(property=re.compile(r'^tw'))) # OK
    
    print(head.findAll(name=re.compile(r'^meta'))) # OK
    print(head.findAll(name=re.compile(r'^tw')))   # empty
    
    print(head.findAll('meta', {'name': re.compile(r'^tw')})) # OK
    

    【讨论】:

      【解决方案2】:

      这是因为name 是标签名称参数的名称,这基本上意味着在这种情况下BeautifulSoup 将查找标签名称以twitter 开头的元素。

      为了指定您实际上是指一个属性,请使用:

      doc.html.head.find_all(attrs={'name': re.compile(r'^twitter')})
      

      或者,通过CSS selector:

      doc.html.head.select("[name^=twitter]")
      

      ^= 表示“以”开头。

      【讨论】:

      • 谢谢!如果我能接受这两个答案,我会的!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      相关资源
      最近更新 更多