2014-12-19 2 views
0

날짜의 텍스트를 찾아서 시스템 날짜로 바꾸고 다른 곳에서 사용하기 위해 이것을 변수로 사용하는 데 어려움을 겪고 있습니다. <span> 태그의 '제목'뒤에있는 날짜를 찾고 있습니다.Python Beautifulsoup 특수 태그 텍스트 찾기

나는 두 가지 방법을 시도했지만 실제로 솔직한 해결책을 제시하지 못했습니다. 마침내 제가 사용했습니다

modif_time = soup.find(text=re.compile('title')) 

여기에 정보가있는 HTML 코드가 있습니다.

<a class="browser-fle yjax-lik" href="/mendonhall/mendonhall_adm/files/e0e854aaf54cb711f7335c8d8ecac9766cd175e3/tak/P0328_dummy.docx">P0328_dummy.docx</a> 
    </td> 
    <td> 
     20.7 KiB 
    </td> 
    <td> 
      application/vnd.openxmlformats-officedocument.wordprocessingml.document 
    </td> 
    <td> 
      <div class="tool" title="tak directory"> 
       <pre>r28ee854af54c</pre> 
      </div> 
    </td> 
    <td> 
      <span class="tool" title="Fri, 19 Dec 2014 09:38:49"> 
      12 minutes and 48 seconds ago</span> 
    </td> 
    <td> 
      <span title="id"> 
      xn06611 (Jeff Mendonhall) 
      </span> 
    </td> 
</tr> 
+0

당신은 아닌'title' 속성을 가진'span' 요소, 태그 사이에 텍스트가 * *를 찾고 있습니다. –

답변

3

당신은 span 태그의 title 속성의 값을 얻기 위해

soup.find("span" title=True, class_='tool') 

를 원한다. title=True은 결과를 title 속성이있는 태그로 제한하고 class_='tool'은 결과가 'tool'class 태그의 결과를 제한합니다. 밑줄은 class_이므로 파이썬 예약어와의 충돌을 피할 수 있습니다.

당신과 함께 날짜 개체에이를 변환 할 수 있습니다

import datetime 
dt = datetime.strptime(soup.find("span" title=True, class_='tool')["title"], "%a, %d %b %Y %H:%M:%S") 
0
from datetime import datetime 

... 

span = soup.find('span') 
title = span['title'] 
print datetime.strptime(title, '%a, %d %b %Y %H:%M:%S') 

출력 :

2014-12-19 09:38:49 
당신은 모든 범위의 요소를 얻고 날짜 만있는 사람을 유지하는 방법를 확인할 수
+0

적어도'find()'는'soup.find ('span', title = True)'로'title' 속성을 찾을 수 있습니다. –

0

"제목"으로. 가 인쇄 여기에서

import time 
import requests 
from bs4 import BeautifulSoup 

html = requests.get(url).content # url you're interested in 

soup = BeautifulSoup(html) 
def is_date(x): 
    try: 
     time.strptime(x, "%a, %d %b %Y %H:%M:%S") # Try to transform string into 
     return True        # a datetime object 
    except: 
     return False 
print is_date("Fri, 19 Dec 2014 09:38:49") # it prints True 

res = [s for s in soup.findAll('span', title=True) if is_date(s['title'])] 
print res 

:

[<span class="tool" title="Fri, 19 Dec 2014 09:38:49"> 
      12 minutes and 48 seconds ago</span>] 
+0

적어도'find_all()'에게'soup.find_all ('span', title = True)로'title' 속성을 찾을 수 있습니다. –

+0

예, 편집 할 때는 이것을 고려합니다. 감사. – DavidK

1

soup.find_all('span')은 HTML의 모든 범위 태그를 찾습니다. 키워드 인수를 지정하여 결과를 further filter 수 있습니다.

import email.utils as EU  
soup.find_all('span', title=EU.parsedate) 

EU.parsedate 가 Truish 값을 반환하는 제목 속성이있는 모든 범위 태그를 찾습니다.

In [112]: EU.parsedate('Fri, 19 Dec 2014 09:38:49') 
Out[112]: (2014, 12, 19, 9, 38, 49, 0, 1, -1) 

EU.parsedate가 제목을 구문 분석 할 수없는 경우 없음 (거짓 값)을 반환합니다.

따라서 soup.find_all('span', title=EU.parsedate)은 title 속성이 날짜처럼 보이는 span 태그 만 찾습니다.

그런 다음 EU.parsedate에서 반환 한 시간 튜플을 datetime.datetime(*timetuple[:6])을 사용하여 datetime.datetime으로 변환 할 수 있습니다.


import bs4 as bs 
import datetime as DT 
import email.utils as EU  

soup = bs.BeautifulSoup(open('data')) 
spans = soup.find_all('span', title=EU.parsedate) 

for span in spans: 
    print(span.attrs['title']) 
    # Fri, 19 Dec 2014 09:38:49 

    timetuple = EU.parsedate(span.attrs['title']) 
    date = DT.datetime(*timetuple[:6]) 
    print(date) 
    # 2014-12-19 09:38:49 
관련 문제