gpt4 book ai didi

python - 使用 "user-agent"字符串时,无法使用 urllib 读取沃尔玛产品页面

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:10 24 4
gpt4 key购买 nike

我正在构建基于 django 的网站,其中一些数据是使用 Ajax 从用户指定的 url 动态加载的。为此,我在 BeautifulSoup 上使用 urllib2 和后来的。我对沃尔玛链接感到奇怪。看一看:

import urllib2
url_to_parse = 'http://www.walmart.com/ip/JVC-HARX300-High-Quality-Full-Size-Headphone/13241375'

# 1 - read the url without user-agent string
opened_url = urllib2.urlopen(url_to_parse)
print len(opened_url.read())
# prints 309316

# 2 - read the url wit user-agent string
headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0' }
req = urllib2.Request(url_to_parse, '', headers)
opened_url = urllib2.urlopen(req)
print len(opened_url.read())
# prints 0

我的问题是为什么在 #2 上打印了一个零?我使用用户代理方法来处理其他网站(如亚马逊)。Wget 能够毫无问题地获取页面内容。

最佳答案

您的问题不在于 User-Agent,而是您的 data 参数。

来自docs :

data may be a string specifying additional data to send to the server, or None if no such data is needed.

沃尔玛似乎不喜欢您的空字符串。将您的调用更改为此:

req = urllib2.Request(url_to_parse, None, headers)

现在两种方式打印相同的值。

关于python - 使用 "user-agent"字符串时,无法使用 urllib 读取沃尔玛产品页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25320937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com