Python Mechanize:上传 UTF-8 文件时出现 UnicodeEncodeError。 “ascii”编解码器
mechanize 框架非常适合自动化前几个网页屏幕。问题在于它需要在表单中上传文件。
以下是错误之前的代码部分:
br.select_form(name="form.uploadXMLDataWizardForm")
xmlFile = codecs.open("MyFile.xml", "rt", "utf8")
br.form.add_file(file_object=xmlFile, content_type="text/xml", filename="MyFile.xml", name="dataFile")
br.submit(name="$action:next")
它会在运行时导致以下错误:
br.submit(name="$action:next")
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 541, in submit
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 530, in click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 2999, in click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 3201, in _click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 2350, in _click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 3269, in _switch_click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 3252, in _request_data
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 1341, in _write_mime_data
UnicodeEncodeError: 'ascii' codec can't encode characters in position 650-651: ordinal not in range(128)
知道如何使 mechanize 处理 UTF-8 文件的上传吗?
the mechanize framework works great for automating the first couple of web screens. The problem is where it needs to upload a file with in a form.
Here is the section of code just before the error:
br.select_form(name="form.uploadXMLDataWizardForm")
xmlFile = codecs.open("MyFile.xml", "rt", "utf8")
br.form.add_file(file_object=xmlFile, content_type="text/xml", filename="MyFile.xml", name="dataFile")
br.submit(name="$action:next")
It results in the following error at runtime:
br.submit(name="$action:next")
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 541, in submit
File "build/bdist.macosx-10.6-universal/egg/mechanize/_mechanize.py", line 530, in click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 2999, in click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 3201, in _click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 2350, in _click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 3269, in _switch_click
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 3252, in _request_data
File "build/bdist.macosx-10.6-universal/egg/mechanize/_form.py", line 1341, in _write_mime_data
UnicodeEncodeError: 'ascii' codec can't encode characters in position 650-651: ordinal not in range(128)
Any idea how to make mechanize handle upload of a UTF-8 file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Mechanize 似乎期望文件数据为原始字节,而不是 Unicode 数据。尝试使用常用的
open()
函数打开文件:Mechanize seems to expect the file data as raw bytes, not Unicode data. Try opening the file using the usual
open()
function: