2012-11-17 2 views
1

다음과 같은 문제가 있습니다 :python html 파싱

나는 html 파일을 구문 분석하고 html 파일에서 링크를 가져오고 싶습니다. 다음 코드로 링크를 얻을 수 있습니다 :

class MyHTMLParser(HTMLParser): 
    links=[] 
    def __init__(self,url): 
     HTMLParser.__init__(self) 
     self.url = url 

    def handle_starttag(self, tag, attrs): 
     try: 
      if tag == 'a': 
       for name, value in attrs: 
        if name == 'href': 
         if value[:5]=="http:": 
          self.links.append(value) 
     except: 
      pass 

그러나 오디오 파일, 비디오 파일 등을 얻고 싶지 않습니다. 단지 HTML 링크 만 얻고 싶습니다. 어떻게해야합니까?

+0

링크 끝을 확인할 수 있으며 특정 형식 인 경우 해당 링크를 목록에 추가하지 않아도됩니다. 다른 방법이 있습니까? –

+0

http://stackoverflow.com/questions/717541/parsing-html-in-python?rq=1 – ppaulojr

답변

3

링크 끝을 확인할 수 있으며 특정 형식 인 경우 목록에 해당 링크를 추가하지 않을 수 있습니다. 다른 방법이 있습니까?

당신은 'Content-Type' 헤더를 볼 수 있었다 :

import urllib2 
url = 'https://stackoverflow.com/questions/13431060/python-html-parsing' 
req = urllib2.Request(url) 
req.get_method = lambda : 'HEAD'  
response = urllib2.urlopen(req) 
content_type = response.headers.getheader('Content-Type') 
print(content_type) 

req.get_method = lambda : 'HEAD'에 대한 @JonClements에

text/html; charset=utf-8 

많은 감사를 얻을 수 있습니다. HEAD 요청을 보내는이 방법과 다른 방법에 대한 자세한 내용은 here을 참조하십시오.

+1

대신 'Range'를 사용하십시오. 아마도'request = urllib2.Request (someurl); request.get_method = lambda : 'HEAD'; response = urllib2.urlopen (request)'그리고 거기에서 계속하십시오 ... –

+0

@JonClements : 정보를 주셔서 대단히 감사합니다. 네가 할 수 있다는 것을 나는 몰랐다. – unutbu

+0

@JonClements :'req.get_method()'가'HEAD'를 리턴한다는 것은 무엇을 의미합니까? [The docs] (http://docs.python.org/2/library/urllib2.html#urllib2.Request.get_method)는 항상'GET' 또는'POST'를 반환한다고합니다 ...? – unutbu