python 在发布到表单时机械化 UnicodeDecodeError

python mechanize UnicodeDecodeError when posting to a form

我尝试使用 mechanize 将脚本制作成 post 形式 脚本:

# Browser
br = mechanize.Browser()

cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open('https://m.bukalapak.com/products/new?category_id=1067')
br.select_form(nr=1)
br.form['product[name']= "My Product"
... #other form handling
br.submit()
print br.response.read()

它returns UnicodeDecodeError

这是我试图 post 到的表格:

<form accept-charset="UTF-8" action="/products" class="simple_form new_product" enctype="multipart/form-data" id="new_product" method="post" novalidate="novalidate"><div style="display:none"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="Qy4y7ZJENkgGAlyYvB68XwAHfWA1iRKUj+p2PzUkywc=" /></div><div class='product-upload-form with-sticky clearfix'>
<input id="product_category_id" name="product[category_id]" type="hidden" value="1067" />

<div class="control-group string required product_name"><label class="string required control-label" for="product_name"><abbr title="required">*</abbr> Nama barang</label><div class="controls"><input class="string required" id="product_name" maxlength="80" name="product[name]" size="80" type="text" /></div></div>

在脚本开头设置编码

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')