2017-12-17 4 views
1

나는 꽤 이해할 수없는 이상한 행동을하고 있습니다. 나는 누군가가 무슨 일이 일어나고 있는지 설명 할 수 있기를 바라고 있습니다.Python Beautiful Soup HTML 메타 데이터 추출

<meta property="og:title" content="This is the Tesla Semi truck"> 
<meta name="twitter:title" content="This is the Tesla Semi truck"> 

이 줄을 성공적으로 ALL "OG"속성을 찾아 목록을 반환

이 메타 데이터를 고려하십시오.

opengraphs = doc.html.head.findAll(property=re.compile(r'^og')) 

그러나이 줄은 지저귐 카드에 대해 동일한 작업을 수행하지 못합니다.

twitterCards = doc.html.head.findAll(name=re.compile(r'^twitter')) 

이유는 첫 번째 라인은 성공적으로 모든 "OG"(오픈 그래프 카드를) 찾을 수 있지만, 트위터 카드를 찾을 수에 실패하는?

답변

2

문제는 특별한 의미를 갖는 name=입니다. 이 태그 이름을 찾는 데 사용됩니다 - 당신의 코드에서 당신은 "meta"을 추가하고 다른 항목 "name"

예와 사전을 사용할 필요가 meta

입니다.

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 
+0

마지막 제안은 완벽하게 작동했습니다. –

3

name 기본적으로이 경우 BeautifulSouptwitter로 시작하는 태그 이름을 가진 요소를 찾을 것을 의미 태그 이름 인수의 이름이기 때문입니다. 당신이 실제로 속성을 의미 지정하기 위해

는 사용

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

또는 CSS selector 비아 :

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

^= 수단 "로 시작".

+0

고맙습니다! 두 가지 대답을 모두 받아 들일 수 있다면 나는 가질 것입니다 !! –

관련 문제