Python을 사용하여 웹 페이지의 페이지 제목을 검색하려면 어떻게해야합니까?


78

Python을 사용하여 웹 페이지의 페이지 제목 (title html 태그)을 검색하려면 어떻게해야합니까?


이 질문이 제기 된 이후로 많은 웹 페이지는 원래 제목을 포함하는 og : title 메타 태그를 사용하기 시작했으며 <title>은 종종 다른 데이터로 접두사 및 접미사가 붙습니다. 처음에는 Facebook에서만 OpenGraph의 일부로 사용되었지만 많은 사이트에서 OpenGraph 메타 데이터를 제공하고 있습니다. og : title은 페이지 제목, 특히 뉴스 기사의 표준 소스가되었습니다.
Nicolas

답변:


64

이러한 작업에는 항상 lxml 을 사용 합니다. Beautifulsoup 도 사용할 수 있습니다 .

import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text

의견에 따라 편집 :

from urllib2 import urlopen
from lxml.html import parse

url = "https://www.google.com"
page = urlopen(url)
p = parse(page)
print p.find(".//title").text

5
위 코드에서 IOError가 발생하는 경우를 대비하여 : stackoverflow.com/questions/3116269/…
Yosh


92

@Vinko Vrsalovic의 답변의 단순화 된 버전은 다음과 같습니다 .

import urllib2
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen("https://www.google.com"))
print soup.title.string

노트:

  • soup.title는 처음 발견 제목 요소 어디서나 HTML 문서의를

  • title.string는 단지이 가정 하나 개의 자식 노드를, 그 자식 노드는 것입니다 문자열

들어 BeautifulSoup로 4.x의 다른 가져 오기를 사용합니다 :

from bs4 import BeautifulSoup

7
감사합니다! 누군가 비슷한 문제가 발생하면 Python3 환경에서 urlllib.request대신 urllib2. 이유가 확실하지 않습니다. 내 파서에 대한 BeautifulSoup 경고를 피하기 위해 soup = BeautifulSoup(urllib.request.urlopen(url), "lxml").
sudo

파이썬 3 import urllib.request as urllib대신 사용import urllib2
blueray

제목 속성이 누락되거나 제목이 비어있는 경우 <title></title>실행시 soup.title.string반환됩니다None
Eitanmg


15

다른 라이브러리를 가져올 필요가 없습니다. 요청에는이 기능이 내장되어 있습니다.

>> hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}
>>> n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders)
>>> al = n.text
>>> al[al.find('<title>') + 7 : al.find('</title>')]
u'Friends (TV Series 1994\u20132004) - IMDb' 

14

mechanize Browser 객체에는 title () 메서드가 있습니다. 따라서이 게시물 의 코드는 다음 과 같이 다시 작성할 수 있습니다.

from mechanize import Browser
br = Browser()
br.open("http://www.google.com/")
print br.title()

11

이것은 아마도 그러한 간단한 작업에는 과잉 일 것입니다. 그러나 그 이상을 수행 할 계획이라면 이러한 도구 (mechanize, BeautifulSoup)에서 시작하는 것이 더 합리적입니다. 대체 도구 (내용 및 정규식을 얻기위한 urllib)보다 훨씬 사용하기 쉽기 때문입니다. 또는 html을 구문 분석하는 다른 파서)

링크 : BeautifulSoup 기계화

#!/usr/bin/env python
#coding:utf-8

from BeautifulSoup import BeautifulSoup
from mechanize import Browser

#This retrieves the webpage content
br = Browser()
res = br.open("https://www.google.com/")
data = res.get_data() 

#This parses the content
soup = BeautifulSoup(data)
title = soup.find('title')

#This outputs the content :)
print title.renderContents()

6

soup.select_one을 사용하여 제목 태그를 타겟팅하십시오.

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('url')
soup = bs(r.content, 'lxml')
print(soup.select_one('title').text)

6

HTMLParser 사용 :

from urllib.request import urlopen
from html.parser import HTMLParser


class TitleParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.match = False
        self.title = ''

    def handle_starttag(self, tag, attributes):
        self.match = tag == 'title'

    def handle_data(self, data):
        if self.match:
            self.title = data
            self.match = False

url = "http://example.com/"
html_string = str(urlopen(url).read())

parser = TitleParser()
parser.feed(html_string)
print(parser.title)  # prints: Example Domain

이 스크립트는 Python 3 용입니다. Python 3.x에서는 HtmlParser 모듈의 이름이 html.parser로 변경되었습니다. 마찬가지로 urllib.request 파이썬 3에 추가되었습니다
satishgoda

1
그것의 아마 더 명시 적으로 문자열로 바이트를 변환하는, r=urlopen(url), encoding = r.info().get_content_charset(),와 html_string = r.read().decode(encoding).
reubano

4

정규식 사용

import re
match = re.search('<title>(.*?)</title>', raw_html)
title = match.group(1) if match else 'No title'

실제로 .group (1)은 무엇입니까? 어떤 참조?
pije76

안녕하세요, group(0)전체 경기를 반환합니다. 참조를 위해 일치 개체 를 참조하십시오.
Finn

1
이 제목 태그가 정확하게 <제목> </ 제목> (대문자, 혼합 된 경우, 간격)으로 형성되지 않은 경우 그리워합니다
누가 복음 Rehmann

제목 태그 내에 다른 데이터가있는 경우 <title. *?>도 포함합니다.
Pranav Wadhwa 19

1

soup.title.string실제로 유니 코드 문자열을 반환합니다. 이를 일반 문자열로 변환하려면 다음을 수행해야합니다. string=string.encode('ascii','ignore')


그것은 당신이 원하는 것이 아닌 비 ASCII 문자를 제거합니다. encode문자열이 아닌 바이트 ( 제공되는 것) 를 정말로 원한다면 올바른 charset. 예 : string.encode('utf-8').
reubano

1

다음은 내결함성 HTMLParser구현입니다. 깨지지 않고
거의 모든 것을 던질 수 있습니다 . get_title()예기치 않은 일 get_title()이 발생 하면 반환 None됩니다. 페이지를 다운로드
할 때 오류를 무시하고 페이지에 사용 된 문자 집합 Parser()ASCII관계없이 페이지를 인코딩 합니다. to_ascii()데이터를 UTF-8또는 다른 인코딩 으로 변환 하기 위해 변경 하는 것은 간단합니다 . 인코딩 인수를 추가하고 함수의 이름을 to_encoding().
기본적 HTMLParser()으로 끊어진 html에서 중단되고 일치하지 않는 태그와 같은 사소한 것에서도 중단됩니다. 이 동작을 방지하기 위해 HTMLParser()의 오류 메서드를 오류를 무시하는 함수 로 대체했습니다 .

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

''' 
Extract the title from a web page using
the standard lib.
'''

from html.parser import HTMLParser
from urllib.request import urlopen
import urllib

def error_callback(*_, **__):
    pass

def is_string(data):
    return isinstance(data, str)

def is_bytes(data):
    return isinstance(data, bytes)

def to_ascii(data):
    if is_string(data):
        data = data.encode('ascii', errors='ignore')
    elif is_bytes(data):
        data = data.decode('ascii', errors='ignore')
    else:
        data = str(data).encode('ascii', errors='ignore')
    return data


class Parser(HTMLParser):
    def __init__(self, url):
        self.title = None
        self.rec = False
        HTMLParser.__init__(self)
        try:
            self.feed(to_ascii(urlopen(url).read()))
        except urllib.error.HTTPError:
            return
        except urllib.error.URLError:
            return
        except ValueError:
            return

        self.rec = False
        self.error = error_callback

    def handle_starttag(self, tag, attrs):
        if tag == 'title':
            self.rec = True

    def handle_data(self, data):
        if self.rec:
            self.title = data

    def handle_endtag(self, tag):
        if tag == 'title':
            self.rec = False


def get_title(url):
    return Parser(url).title

print(get_title('http://www.google.com'))

0

lxml 사용 ...

Facebook opengraph 프로토콜에 따라 태그가 지정된 페이지 메타에서 가져 오기 :

import lxml.html.parse
html_doc = lxml.html.parse(some_url)

t = html_doc.xpath('//meta[@property="og:title"]/@content')[0]

또는 lxml과 함께 .xpath 사용 :

t = html_doc.xpath(".//title")[0].text
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.