2011-02-13 5 views
0

HTML Webページからhtmlとpdfsの両方を取得するために正規表現パターンとして渡す必要があるものはありますか?これまでのところ、私が持っているものは以下の通りです。 OR文を使用する必要があると仮定しましたが、実際には期待どおりに機能しませんでした。BeautifulSoup SoupStrainerひずみhtmlとpdfリンク

status, response = http.request("http://www.example.com") 
htmlandpdfonly=SoupStrainer('a', href=re.compile('html|pdf')) 
for link in BeautifulSoup(response, parseOnlyThese = htmlandpdfonly): 
    if(link.has_key('href')): 
     print link['href'] 

答えて

3
import re 
from BeautifulSoup import BeautifulSoup 

# find ".html" or ".pdf" in a string 
match = re.compile('\.(html|pdf)') 

# parse page content 
status, response = http.request("http://www.example.com") 
page = BeautifulSoup(response) 

# check links 
for link in page.findAll('a'): 
    try: 
     href = link['href'] 
     if re.search(match, href): 
      print href 
    except KeyError: 
     pass 
関連する問題