gpt4 book ai didi

python - Beautifulsoup 在元标记中找到特定值

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:17 26 4
gpt4 key购买 nike

我正在尝试查找其中包含作者的所有元标记。如果我有一个特定的键和 Regex 值,它就可以工作。当两者都是正则表达式时,它不起作用。是否可以提取页面上包含“作者”关键字的所有元标记?这是我写的代码。

from bs4 import BeautifulSoup
page = requests.get(url)
contents = page.content
soup = BeautifulSoup(contents, 'lxml')
preys = soup.find_all("meta", attrs={re.compile('.*'): re.compile('author')})

编辑:为澄清起见,我要具体解决的问题是值“author”是否映射到任何键。正如我在各种示例中看到的那样,该键可以是“itemprop”、“name”甚至“property”。基本上,我的问题是提取所有将作者作为其中的值的元标记,而不管该值具有什么键。几个例子就是这样:

<meta content="Jami Miscik" name="citation_author"/>
<meta content="Will Ripley, Joshua Berlinger and Allison Brennan, CNN" itemprop="author"/>
<meta content="Alison Griswold" property="author"/>

最佳答案

如果您正在寻找 citation_authorauthor,您可能会使用 soup.select() 和常规的组合表达式:

from bs4 import BeautifulSoup
import re

# some test string
html = '''
<meta name="author" content="Anna Lyse">
<meta name="date" content="2010-05-15T08:49:37+02:00">
<meta itemprop="author" content="2010-05-15T08:49:37+02:00">
<meta rel="author" content="2010-05-15T08:49:37+02:00">
<meta content="Jami Miscik" name="citation_author"/>
<meta content="Will Ripley, Joshua Berlinger and Allison Brennan, CNN" itemprop="author"/>
<meta content="Alison Griswold" property="author"/>
'''

soup = BeautifulSoup(html, 'html5lib')

rx = re.compile(r'(?<=)"(?:citation_)?author"')

authors = [author
for author in soup.select("meta")
if rx.search(str(author))]

print(authors)

关于python - Beautifulsoup 在元标记中找到特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44527583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com