使用BeautifulSoup和Python获取元标记内容属性

时间:2016-04-21 11:22:18

标签: python html web-scraping beautifulsoup

我正在尝试使用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:内容太棒了!

5 个答案:

答案 0 :(得分:33)

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")

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

答案 1 :(得分:11)

试试这个:

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)

答案 2 :(得分:2)

我要解决的方法如下:
(与属性列表一起使用时更整洁...)

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

答案 3 :(得分:1)

来自 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()

答案 4 :(得分:0)

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

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'