2012-12-22 112 views
0

试图打开一个URL时,我得到一个406错误与机械化:406错误与机械化

for url in urls: 
    if "http://" not in url: 
     url = "http://" + url 
    print url 
    try: 
     page = mech.open("%s" % url) 
    except urllib2.HTTPError, e: 
     print "there was an error opening the URL, logging it" 
     print e.code 
     logfile = open ("log/urlopenlog.txt", "a") 
     logfile.write(url + "," + "couldn't open this page" + "\n") 
     continue 
    else: 
     print "opening this URL..." 
     page = mech.open(url) 

任何想法会导致出现406错误?如果我转到有问题的网址,我可以在浏览器中打开它。

+0

没有必要使用插值:'page = mech.open(url)'会做得很好(虽然不是解决你的问题)。 –

+1

406错误是非常特定于Web服务器。它意味着*无论如何服务器都不喜欢你的Accept头。 –

+1

[406意味着服务器不喜欢你的头文件](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)你可以发布机械化发送的头文件吗? –

回答

2

尝试根据浏览器发送的内容向请求添加标题;从添加Accept标题开始(406通常意味着服务器不喜欢你想要接受的内容)。

参见"Adding headers"文档中:

req = mechanize.Request(url) 
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') 
page = mechanize.urlopen(req) 

Accept头值有基于由铬所发送的报头。

+0

嗯......似乎没有做到这一点。仍然得到相同的错误。 – user1328021

+0

@ user1328021:这完全取决于服务器,没有简单的答案。在访问相同的URL之前添加您发现浏览器发送的标题,直到其可用。 –

+0

我的浏览器显示它正在发送上述确切的标题。接受语言或接受编码怎么样?那些会有效果吗? – user1328021

0

如果你想找出哪些邮件头。您的浏览器发送,此网页并将其显示出来:https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending

“接受”和“用户代理”头应该够了。这是我做了什么,摆脱错误的:

#establish counter 
j = 0 

#Create headers for webpage 
headers = {'User-Agent': 'Mozilla/5.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'} 

#Create for loop to get through list of URLs 
for url in URLs: 

    #Verify scraper agent so that web security systems don't block webpage scraping upon URL opening, with j as a counter 
    req = mechanize.Request(URLs[j], headers = headers) 

    #Open the url 
    page = mechanize.urlopen(req) 

    #increase counter 
    j += 1 

您也可以尝试导入“的urllib2”或“urllib的”库中打开这些网址。语法是一样的。