【问题标题】:Get meta tag content property with BeautifulSoup and Python使用 BeautifulSoup 和 Python 获取元标记内容属性
【发布时间】:2016-08-14 13:32:35
【问题描述】:

我正在尝试使用python和美汤提取下面标签的内容部分:

<meta property="og:title" content="Super Fun Event 1" />
<meta property="og:url" content="http://superfunevents.com/events/super-fun-event-1/" />

我正在让 BeautifulSoup 很好地加载页面并找到其他东西(这也从隐藏在源中的 id 标记中获取文章 id),但我不知道搜索 html 并找到的正确方法这些位,我尝试了 find 和 findAll 的变体,但无济于事。该代码目前遍历了一个 url 列表...

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#importing the libraries
from urllib import urlopen
from bs4 import BeautifulSoup

def get_data(page_no):
    webpage = urlopen('http://superfunevents.com/?p=' + str(i)).read()
    soup = BeautifulSoup(webpage, "lxml")
    for tag in soup.find_all("article") :
        id = tag.get('id')
        print id
# the hard part that doesn't work - I know this example is well off the mark!        
    title = soup.find("og:title", "content")
    print (title.get_text())
    url = soup.find("og:url", "content")
    print (url.get_text())
# end of problem

for i in range (1,100):
    get_data(i)

如果有人能帮我整理一下,找到 og:title 和 og:content 那就太好了!

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    提供meta 标记名称作为find() 的第一个参数。然后,使用关键字参数来检查具体属性:

    title = soup.find("meta", property="og:title")
    url = soup.find("meta", property="og:url")
    
    print(title["content"] if title else "No meta title given")
    print(url["content"] if url else "No meta url given")
    

    如果您知道 title 和 url 元属性将始终存在,则此处的 if/else 检查将是可选的。

    【讨论】:

    • 没有内置的获取内容,否则回退到默认?
    • @ChristopheRoussy 是的,这正是答案中显示的内容。此外,您可以使用soup.find("meta", property="og:title", content=True) 来加强content 属性的存在。谢谢。
    【解决方案2】:

    试试这个:

    soup = BeautifulSoup(webpage)
    for tag in soup.find_all("meta"):
        if tag.get("property", None) == "og:title":
            print tag.get("content", None)
        elif tag.get("property", None) == "og:url":
            print tag.get("content", None)
    

    【讨论】:

    • 两年后,这正是我根据同一标签的另一个属性的值从元标签的一个属性中获取值所需要的。谢谢!
    【解决方案3】:

    我喜欢解决这个问题的方法如下:
    (使用属性列表查找时更整洁...)

    title = soup.find("meta",  {"property":"og:title"})
    url = soup.find("meta",  {"property":"og:url"})
    
    # Using same method as above answer
    title = title["content"] if title else None
    url = url["content"] if url else None
    

    【讨论】:

      【解决方案4】:

      您可以使用gazpacho 获取元标记内的内容:

      from gazpacho import Soup
      
      html = """\
      <meta property="og:title" content="Super Fun Event 1" />
      <meta property="og:url" content="http://superfunevents.com/events/super-fun-event-1/" />
      """
      
      soup = Soup(html)
      soup.find("meta", {"property": "og:title"}).attrs['content']
      

      哪个会输出:

      'Super Fun Event 1'
      

      【讨论】:

        【解决方案5】:

        来自 Jinesh Narayanan 的代码:https://gist.github.com/jineshpaloor/6478011 对此讨论有效。

        from bs4 import BeautifulSoup
        import requests
        def main():
            r = requests.get('http://www.sourcebits.com/')
            soup = BeautifulSoup(r.content, features="lxml")
        
            title = soup.title.string
            print ('TITLE IS :', title)
        
            meta = soup.find_all('meta')
        
            for tag in meta:
                if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['description', 'keywords']:
                    # print ('NAME    :',tag.attrs['name'].lower())
                    print ('CONTENT :',tag.attrs['content'])
        
        if __name__ == '__main__':
            main()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-21
          • 1970-01-01
          • 1970-01-01
          • 2022-11-14
          • 2017-08-17
          • 2017-08-28
          相关资源
          最近更新 更多