Python을 사용하여 웹 페이지의 페이지 제목 (title html 태그)을 검색하려면 어떻게해야합니까?
Python을 사용하여 웹 페이지의 페이지 제목 (title html 태그)을 검색하려면 어떻게해야합니까?
답변:
이러한 작업에는 항상 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
@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
urlllib.request대신 urllib2. 이유가 확실하지 않습니다. 내 파서에 대한 BeautifulSoup 경고를 피하기 위해 soup = BeautifulSoup(urllib.request.urlopen(url), "lxml").
import urllib.request as urllib대신 사용import urllib2
<title></title>실행시 soup.title.string반환됩니다None
다른 라이브러리를 가져올 필요가 없습니다. 요청에는이 기능이 내장되어 있습니다.
>> 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'
이것은 아마도 그러한 간단한 작업에는 과잉 일 것입니다. 그러나 그 이상을 수행 할 계획이라면 이러한 도구 (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()
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
r=urlopen(url), encoding = r.info().get_content_charset(),와 html_string = r.read().decode(encoding).
정규식 사용
import re
match = re.search('<title>(.*?)</title>', raw_html)
title = match.group(1) if match else 'No title'
soup.title.string실제로 유니 코드 문자열을 반환합니다. 이를 일반 문자열로 변환하려면 다음을 수행해야합니다.
string=string.encode('ascii','ignore')
encode문자열이 아닌 바이트 ( 제공되는 것) 를 정말로 원한다면 올바른 charset. 예 : string.encode('utf-8').
다음은 내결함성 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'))