Python Beautiful Soup 提取 HTML 元数据

Tyl*_*ell 2 html python twitter beautifulsoup web-scraping

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

考虑这个元数据:

<meta property="og:title" content="This is the Tesla Semi truck">
<meta name="twitter:title" content="This is the Tesla Semi truck">
Run Code Online (Sandbox Code Playgroud)

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

opengraphs = doc.html.head.findAll(property=re.compile(r'^og'))
Run Code Online (Sandbox Code Playgroud)

然而,这条线不能为 twitter 卡做同样的事情。

twitterCards = doc.html.head.findAll(name=re.compile(r'^twitter'))
Run Code Online (Sandbox Code Playgroud)

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

fur*_*ras 5

问题是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
Run Code Online (Sandbox Code Playgroud)