python - 按名称、beautiful soup 和 python 获取元标记内容

标签 python html web-scraping beautifulsoup metadata

我正在尝试从该网站获取元数据(这是代码)。

import requests
from bs4 import BeautifulSoup

source = requests.get('https://www.svpboston.com/').text

soup = BeautifulSoup(source, features="html.parser")

title = soup.find("meta", name="description")
image = soup.find("meta", name="og:image")

print(title["content"] if title else "No meta title given")
print(image["content"]if title else "No meta title given")

但是我收到此错误。

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/Work/Web Scraping/Selenium/sadsaddas.py", line 9, in <module>
    title = soup.find("meta", name="description")
TypeError: find() got multiple values for argument 'name'

有什么想法吗?

最佳答案

来自 bs4 docs :

You can't use a keyword argument to search for HTML’s name element, because Beautiful Soup uses the name argument to contain the name of the tag itself. Instead, you can give a value to ‘name’ in the attrs argument

要按特定属性抓取标签,我建议您将其放入字典中并将该字典传递给 .find()作为attrs争论。但是您也传递了错误的属性来获取标题和图像。你应该捕获 meta标记为 property=<...>而不是name=<...> 。以下是获得所需内容的最终代码:

import requests
import requests
from bs4 import BeautifulSoup

source = requests.get('https://www.svpboston.com/').text

soup = BeautifulSoup(source, features="html.parser")

title = soup.find("meta", attrs={'property': 'og:title'})
image = soup.find("meta", attrs={'property': 'og:image'})

print(title["content"] if title is not None else "No meta title given")
print(image["content"] if title is not None else "No meta title given")

关于python - 按名称、beautiful soup 和 python 获取元标记内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66533085/

相关文章:

python - 将字符串转换为带有内部逗号的字符串字典

python - 在 matplotlib 中,如何绘制多个数据集的条形图以将最小的条放在前面?

python - Numpy:如何将颜色矩阵转换为扁平向量

html - 图片上的 anchor 在 IE 10 中不可点击,但在 IE 11、Firefox 和 Chrome 中有效

Python 错误 : 'utf8' codec can't decode byte 0x92 in position 85: invalid start byte

python - 为什么创建分层条形图会删除排序?

html - 加入游戏框架

html - 使用不同颜色的样式列表项

python - 即使收到 200 状态代码也重试 Scrapy 请求

javascript - 使用 Apps 脚本抓取 javascript 渲染的网页