2013-11-25 3 views
0

큰 덩어리의 텍스트가 있고이 패턴을 따르는 URL 목록을 반환하는 모든 URL을 구문 분석하고 싶습니다. https://www.facebook.com/. * $. 여기 텍스트 블록에서 URL을 가져 오는 중입니까?

내가에서 분석하고자하는 텍스트의 예입니다

<abbr title="Monday xxxx" data-utime="xx" class="timestamp">over a year ago</abbr></div></div></div></div></div></li><li class="fbProfileBrowserListItem"><div class="clearfix _5qo4"><a class="_8o _8t lfloat" href="https://www.facebook.com/xxxxx?fref=pb&amp;hc_location=profile_browser" tabindex="-1" aria-hidden="true" data-hovercard="/ajax/hovercard/user.php?id=xxxx&amp;extragetparams=%7B%22hc_location%22%3A%22profile_browser%22%7D"><img class="_s0 _rw img" src="https://fbcdn-profile-xxxxxxxx.net/hprofile-ak-ash2/xxxxxx.jpg" alt=""></a><div class="clearfix _42ef"><div class="_6a rfloat"><div class="_6a _6b" style="height:50px"></div><div class="_6a _6b"><div class="_5t4x"><div class="FriendButton" id="u_2h_1w"><button class="_42ft _4jy0 FriendRequestAdd addButton _4jy3 _517h" type="button"> 

내가 좀하고 싶습니다 내가 뭘하려 "https://www.facebook.com/xxxxx?fref=pb&hc_location=profile_browser"

from bs4 import BeautifulSoup 
html = open('full_page_firefox.html') 
def getLinks(html): 
    soup = BeautifulSoup(html) 
    anchors = soup.findAll('a') 
    links = [] 
    for a in anchors: 
     links.append(a['href']) 
    return links 
print getLinks(html) 

분할은 패턴을 유지하지 않기 때문에 작동하지 않는 것처럼 보입니다. 그래서 내가 "https://www.facebook.com/ *. $"와 같은 URL을 사용하여 re.split() 또는 무엇인가로 URL을 얻으면 작동하지 않습니다.

+0

희망 사항이 블로그 게시물은 누군가에게 유용 할 수 있기를 바랍니다. http://samranga.blogspot.com/2015/08/web-scraping-beginner-python.html –

답변

1

여기에서 코드가 작동하는지, 입력 파일을 확인하고, 아름다운 비누가 구문 분석 할 수 있는지 확인하십시오.

은 BTW, 또한

from lxml import etree 
print etree.parse('full_page_firefox.html').xpath('//a/@href | //img/@src') 

['https://www.facebook.com/xxxxx?fref=pb&hc_location=profile_browser', 
'https://fbcdn-profile-xxxxxxxx.net/hprofile-ak-ash2/xxxxxx.jpg'] 
1

귀하의 기능이 작동하는 LXML을 사용하는 것이 좋습니다. 내가 제공 한 html 파일을 html 파일에 복사하고 좋은 측정을 위해 <html><body> 태그를 추가했습니다. 파이썬 인터프리터에서

with open('C:/users/brian/desktop/html.html') as html: 
    print getLinks(html) 

을 다음과 같은 출력을 가지고 :

은 그 때 나는 노력이에

[u'https://www.facebook.com/xxxxx?fref=pb&hc_location=profile_browser'] 

전화 str을 당신은

1

당신이 URL을 확인할 수 있습니다 좋은 것 BS에서 파싱 한 패턴은 다음과 같습니다.

from bs4 import BeautifulSoup 
import re 
html = open('full_page_firefox.html') 
def getLinks(html): 
    soup = BeautifulSoup(html) 
    anchors = soup.findAll('a') 
    links = [] 
    for a in anchors: 
     match_result = re.match(r'https://www.facebook.com/.*$', a['href']) 
     if match_result is not None: 
      links.append(match_result.string) 
    return links 
print getLinks(html) 

참고 : '/'와 '.'사이에 공백이 없습니다. 2. '$'는 문자열의 끝과 일치하므로 사용하는 데주의하십시오.

관련 문제