Python 的 urllib2 遵循 3xx 重定向以获得最终内容。有没有办法让 urllib2(或其他一些库,如 httplib2)也遵循 meta refreshes ?或者我是否需要为刷新元标记手动解析 HTML?
最佳答案
这是一个使用 BeautifulSoup 和 httplib2(以及基于证书的身份验证)的解决方案:
import BeautifulSoup
import httplib2
def meta_redirect(content):
soup = BeautifulSoup.BeautifulSoup(content)
result=soup.find("meta",attrs={"http-equiv":"Refresh"})
if result:
wait,text=result["content"].split(";")
if text.strip().lower().startswith("url="):
url=text.strip()[4:]
return url
return None
def get_content(url, key, cert):
h=httplib2.Http(".cache")
h.add_certificate(key,cert,"")
resp, content = h.request(url,"GET")
# follow the chain of redirects
while meta_redirect(content):
resp, content = h.request(meta_redirect(content),"GET")
return content
关于python - 如何在 Python 中跟踪元刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2318446/