我正在尝试使用 python 和 beautiful soup 来提取以下标签的内容部分:
<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 那太棒了!
原文由 the_t_test_1 发布,翻译遵循 CC BY-SA 4.0 许可协议
提供
meta
标记名称作为find()
的第一个参数。然后,使用关键字参数来检查特定的属性:if
/else
如果您知道标题和 url 元属性将始终存在,则这里的检查是可选的。