2016-06-07 4 views
0

모든 전자 메일을 추출하려는 데이터 덤프가 있습니다. 파이썬을 사용하여 데이터 덤프에서 전자 메일 추출

import urllib2 
import re 
from bs4 import BeautifulSoup 
url = urllib2.urlopen("file:///users/home/Desktop/emails.html").read() 
soup = BeautifulSoup(url) 
email = raw_input(soup) 
match = re.findall(r'<(.*?)>', email) 
if match: 
    print match 

샘플 데이터 나 이메일이 <> 태그 사이에 나열되어 있는지 명확하게 볼 수 있습니다

<tr><td><a href="http://abc.gov.com/comments/24-April/file.html">for educational purposes only</a></td> 
<td>7418681641 &lt;[email protected]&gt;</td> 
<td>[email protected]</td> 
<td nowrap="">24-04-2015 10.31</td> 
<td align="center">&nbsp;</td></tr> 
<tr><td><a href="http://abc.gov.com/comments/24-April/test.html">no_subject</a></td> 
<td>John &lt;[email protected]&gt;</td> 
<td>[email protected]</td> 
<td nowrap="">24-04-2015 11.28</td> 
<td align="center">&nbsp;</td></tr> 
<tr><td><a href="http://abc.gov.com/comments/24-April/test.html">something</a></td> 
<td>Mark &lt;[email protected]&gt;</td> 
<td>[email protected]</td> 
<td nowrap="">24-04-2015 11.28</td> 
<td align="center">&nbsp;</td></tr> 
<tr><td><a href="http://abc.gov.com/comments/24-April/abc.html">some data</a></td> 

덤프 내가 BeautifulSoup로

를 사용하여 작성한 코드입니다. 모든 전자 메일을 식별하고 인쇄 할 정규식을 사용하려고합니다. 그러나 실행시 전자 메일 (한 줄에 하나의 전자 메일) 만 추출하는 대신 전체 파일이 인쇄됩니다.

어떻게 해결할 수 있습니까?

+1

작동 (나는 a.html로 샘플 파일을 저장 한). 'urllib2'를 사용하여 로컬 파일을 여는 이유는 무엇입니까? 그냥 f : soup = BeautifulSoup (f)'로 open ("/ path/to/file.html")을 사용하십시오. 다음으로,'raw_input (soup)'이 무엇을 기대합니까? 마지막으로, HTML 파서를 사용하기 시작했을 때 텍스트의 정규식 검색을 수행하는 이유는 무엇입니까? – MattDMo

+0

@MattDMo : 아하, 네가 맞다. raw_input이 사용자로부터 입력을 받았다는 것을 알지 못했습니다. 나는 수프 변수를 문자열로 구문 분석 할 것이라는 가정하에있었습니다. raw_input 라인이 없다면, re.findall 함수가 문자열의 두 번째 파라미터로 문자열을 기대하고 있다고 말하는 오류가 발생했습니다. – Piyush

답변

-1

find_all 방법을 사용하여 찾고있는 태그를 구문 분석 할 수 있습니다. BeautifulSoup. 여기에 코드가 있습니다.

from bs4 import BeautifulSoup 
url = open("a.html",'r').read() 
soup = BeautifulSoup(url) 
rows = soup.find_all('tr') # find all rows using tag 'tr' 
for row in rows: 
    cols = row.find_all('td') # find all columns using 'td' tag 
    if len(cols)>1: 
     email_id_string = cols[1].text # get the text of second element of list (contains email id element) 
     email_id = email_id_string[ email_id_string.find("<")+1 : email_id_string.find(">") ] (get only the email id between <and>) 
     print email_id 
+0

이메일 주소를 포함하지 않는 ''요소가 많기 때문에이 방법이 작동하지 않습니다. – MattDMo

+0

전자 메일 ID가있는 경우 두 번째 열로 표시되므로 '조건'을 사용하여 확인했습니다. – Tanu

+0

아니요. ''당 두 개 이상의 ''요소가 있는지 단순히 확인 했으므로 두 번째 td를 가져 와서 임의의 HTML에 대한 유효한 가정이 아닌 전자 메일이 있다고 가정합니다. OP는 아주 간단한 예제를 게시 한 반면, 실제 데이터는 이와 같이 잘 구조화되어 있지 않다고 생각합니다. 솔루션은 현재보다 훨씬 강력해야합니다. – MattDMo

1

귀하의 예를 실제로 내가 모든 코드를 이해하지 못하는

re.findall(r'\&lt;(.*?)\&gt;',your_data_bump)= 
['[email protected]', '[email protected]', '[email protected]'] 
+0

감사합니다. 실제로이 작업이 이루어졌습니다. 간단히이 줄을 re.findall (r '< (. *?) >', str (email))과 일치하도록 변경 한 다음 값을 인쇄했습니다. – Piyush

관련 문제