python - 在 Python 中使用 urlopen() 防止 "hidden"重定向

标签 python beautifulsoup urllib urlopen

我正在使用 BeautifulSoup 进行网页抓取,但在使用 urlopen 时我遇到了特定类型网站的问题。网站上的每个项目都有自己独特的页面,并且项目有不同的格式(例如:500 mL、1L、2L,...)。

当我使用 Internet 浏览器打开产品的 URL (www.example.com/product1) 时,我会看到一张 500 mL 格式的图片,相关信息 (价格、数量、口味等)以及该特定商品可用的所有其他格式的列表。如果单击另一种格式(例如:1L),图片和有关该项目的信息会发生变化,但浏览器顶部的 URL 会保持不变(www.example. com/product1).但是,通过检查页面的 HTML 代码,我知道所有格式都有自己唯一的 URL(500 mL:www.example.com/product1/123;1L:www.example.com/product1/456, ...)。在我的互联网浏览器中使用 1L 格式的唯一 URL 时,我会自动重定向到页面 www.example.com/product1 但页面上显示的图片和信息对应于 1L 格式. HTML 代码还包含我需要的有关 1L 格式的信息。

当我使用 urlopen 打开这些唯一的 URL 时,我的问题就出现了。

from bs4 import BeautifulSoup 
from urllib import urlopen
webpage = urlopen('www.example.com/product1/456')
soup=BeautifulSoup(webpage)
print soup    

汤中包含的信息对应于使用我的互联网浏览器为唯一 URL 显示的信息:www.example.com/product1/456。它为我提供了有关 www.example.com/product1 上默认显示的项目格式的信息,该格式始终为 500 mL 格式。

有什么方法可以阻止这种重定向,从而允许我使用 BeautifulSoup 捕获唯一 URL 的 HTML 代码中包含的信息?

最佳答案

import urllib2

class RedirectHandler(urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, headers):
        result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
        result.status = code
        return result
    http_error_301 = http_error_303 = http_error_307 = http_error_302

opener = urllib2.build_opener(RedirectHandler())
webpage = opener.open('http://www.example.com/product1/456')
...

关于python - 在 Python 中使用 urlopen() 防止 "hidden"重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974321/

相关文章:

python - 模板语法错误 : widget_tweaks is not a valid library django

python - 使用可变长度 arg 列表创建绑定(bind)到 C 函数的 ctypes

python - 在 opencv python (cv2) 中调整透明图像的大小

python-3.x - 如何使用Python 3并行下载和解析HTML文件?

python - 使用 urllib 登录站点

python - 有没有办法在 for 循环中更改函数中使用的变量?

python - KeyError : 'url_encoded_fmt_stream_map'

python - replaceWith() 后的 find() 不起作用(使用 BeautifulSoup)

python - 如何从 urllib.request 获取 cookie?

python - 如何使用 Python 发送没有 'Host Header' 的请求?