簡體   English   中英

按名稱、美湯和 python 獲取元標記內容

[英]Get meta tag content by name, beautiful soup and python

我正在嘗試從該網站獲取元數據(這是代碼)。

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'

有任何想法嗎?

你可以這樣嘗試

title = soup.find("meta", attrs={"name":"description"})
image = soup.find("meta", attrs={"name":"og:image"})
print(title)
print(image)
print(title["content"] if title else "No meta title given")
print(image["content"] if image else "No meta for image given")

或者

title = soup.find("meta", property="og:title")
print(title["content"] if title else "No meta title given")

來自bs4 docs

您不能使用關鍵字參數來搜索 HTML 的name元素,因為 Beautiful Soup 使用 name 參數來包含標簽本身的名稱。 相反,您可以在 attrs 參數中為“name”賦值

要按特定屬性獲取標簽,我建議您將其放入字典並將該字典傳遞給.find()作為attrs參數。 但是您也傳遞了錯誤的屬性來獲取標題和圖像。 您應該使用property=<...>而不是name=<...>來獲取meta標記。 以下是獲得所需內容的最終代碼:

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")

find() 只接受一個參數。 改用這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM