【问题标题】:Python Follow Window.Location RedirectPython 跟随 Window.Location 重定向
【发布时间】:2023-04-01 07:03:01
【问题描述】:

我创建了一个快速的 Python 程序,它返回 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 重定向?

【问题讨论】:

  • 遍历脚本,使用适当的正则表达式找到文本window.location = "...",转到匹配的字符串。

标签: python beautifulsoup urllib2


【解决方案1】:

我最终使用 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','')

【讨论】:

    猜你喜欢
    • 2012-01-05
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多