Skip to main content
 首页 » 编程设计

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

2024年10月25日27落叶无声

我正在构建基于 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) 

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