Python 关注 Window.Location 重定向
Python Follow Window.Location Redirect
我创建了一个快速 python 程序,returns 标题为 URL 的最终目的地。
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())
此代码工作正常,但其中一个 URL 具有通过 window.location
完成的重定向,因此我的脚本无法遵循该路径。有没有一种简单的方法让它也遵循 window.location
重定向?
我最终使用 RegEx 来匹配 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','')
我创建了一个快速 python 程序,returns 标题为 URL 的最终目的地。
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())
此代码工作正常,但其中一个 URL 具有通过 window.location
完成的重定向,因此我的脚本无法遵循该路径。有没有一种简单的方法让它也遵循 window.location
重定向?
我最终使用 RegEx 来匹配 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','')