如何在Python中遵循元刷新

发布于 2021-01-29 18:23:43

Python的urllib2遵循3xx重定向以获取最终内容。有没有办法使urllib2(或其他一些库,例如httplib2)也遵循元刷新?还是我需要为刷新meta标签手动解析HTML?

关注者
0
被浏览
42
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    好的,似乎没有库支持它,因此我一直在使用以下代码:

    import urllib2
    import urlparse
    import re
    
    def get_hops(url):
        redirect_re = re.compile('<meta[^>]*?url=(.*?)["\']', re.IGNORECASE)
        hops = []
        while url:
            if url in hops:
                url = None
            else:
                hops.insert(0, url)
                response = urllib2.urlopen(url)
                if response.geturl() != url:
                    hops.insert(0, response.geturl())
                # check for redirect meta tag
                match = redirect_re.search(response.read())
                if match:
                    url = urlparse.urljoin(url, match.groups()[0].strip())
                else:
                    url = None
        return hops
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看