Python美丽的汤提取HTML元数据

问题描述 投票:1回答:2

我得到一些我不太明白的奇怪行为。我希望有人可以解释发生了什么。

考虑这个元数据:

<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卡),但未能找到推特卡?

python html twitter web-scraping beautifulsoup
2个回答
2
投票

问题是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

3
投票

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

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

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

或者,通过CSS selector

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

其中^=的意思是“以...开头”。

© www.soinside.com 2019 - 2024. All rights reserved.