2015-11-19 71 views
1

我創建了一個快速python程序,它返回URL的最終目標的標題。Python關注Window.Location重定向

def get_title(url): 
    try: 
     req = urllib2.Request(url) 
     soup = BeautifulSoup(urllib2.urlopen(req)) 
     return soup.title.string.encode('ascii', 'ignore').strip().replace('\n','') 
    except: 
     print('Generic Exception for ' + url + ', ' + traceback.format_exc()) 

此代碼工作正常,但該網址中的一個具有通過window.location做,因爲這個我的腳本不能走這條道路重定向。有沒有簡單的方法讓它也遵循window.location重定向?

+1

遍歷腳本,查找文本'了window.location =「...」'使用適當的正則表達式,去匹配的字符串。 – kay

回答

1

我結束了使用正則表達式匹配window.location並提取URL

def get_title(url): 
    try: 
     req = urllib2.Request(url) 
     soup = BeautifulSoup(urllib2.urlopen(req)) 
     redirMatch = re.match(r'.*?window\.location\s*=\s*\"([^"]+)\"', str(soup), re.M|re.S) 
     if(redirMatch and "http" in redirMatch.group(1)): 
      url = redirMatch.group(1) 
      return get_title(url) 
     else: 
      return soup.title.string.encode('ascii', 'ignore').strip().replace('\n','')