使用Python 3,我从URL请求json文档.
response = urllib.request.urlopen(request)
Run Code Online (Sandbox Code Playgroud)
该response
对象是一个类似文件的对象read
和readline
方法.通常,可以使用以文本模式打开的文件创建JSON对象.
obj = json.load(fp)
Run Code Online (Sandbox Code Playgroud)
我想做的是:
obj = json.load(response)
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为urlopen以二进制模式返回文件对象.
当然,解决方法是:
str_response = response.read().decode('utf-8')
obj = json.loads(str_response)
Run Code Online (Sandbox Code Playgroud)
但这感觉很糟糕......
有没有更好的方法可以将字节文件对象转换为字符串文件对象?或者我错过任何参数urlopen
或json.load
给出编码?
我正在编写一个Python(Python 3.3)程序,使用POST方法将一些数据发送到网页.主要用于调试过程我得到页面结果并使用print()
函数在屏幕上显示它.
代码是这样的:
conn.request("POST", resource, params, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data.decode('utf-8'));
Run Code Online (Sandbox Code Playgroud)
该HTTPResponse
.read()
方法返回一个bytes
编码页面的元素(这是一个结构良好的UTF-8文档)在我停止使用Windows的IDLE GUI并使用Windows控制台之前,这似乎没问题.返回的页面有一个U + 2014字符(em-dash),打印功能可以在Windows GUI中很好地转换(我假定代码页1252),但不在Windows控制台中(代码页850).鉴于strict
默认行为,我收到以下错误:
UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in position 10248: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我可以使用这个非常难看的代码修复它:
print(data.decode('utf-8').encode('cp850','replace').decode('cp850'))
Run Code Online (Sandbox Code Playgroud)
现在用一个替换有问题的字符" - " ?
.不是理想的情况(连字符应该是一个更好的替代品),但足够我的目的.
我的解决方案中有几件我不喜欢的东西.
问题不在于emdash(我可以想到解决这个问题的几种方法),但我需要编写健壮的代码.我正在向页面提供来自数据库的数据,并且数据可以返回.我可以预见到许多其他相互矛盾的情况:'Á'U+ 00c1(在我的数据库中可能)可以转换为CP-850(西欧语言的DOS/Windows控制台编码)但不能转换为CP-437(美国的编码)英语,在许多Windows instalations中是默认的).
那么,问题是:
有没有更好的解决方案使我的代码与输出接口编码无关?
我需要存储可以使用任何语言的网站内容.我需要能够在内容中搜索Unicode字符串.
我尝试过类似的东西:
import urllib2
req = urllib2.urlopen('http://lenta.ru')
content = req.read()
Run Code Online (Sandbox Code Playgroud)
内容是一个字节流,所以我可以在其中搜索Unicode字符串.
我需要一些方法,当我这样做urlopen
,然后阅读使用标题中的charset解码内容并将其编码为UTF-8.
我想操纵这个网址上的信息.我可以成功打开它并阅读其内容.但我真正想要做的就是抛弃我不想要的所有东西,并操纵我想要保留的东西.
有没有办法将字符串转换为字典,以便我可以迭代它?或者我只需按原样解析它(str类型)?
from urllib.request import urlopen
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
print(response.read()) # returns string with info
Run Code Online (Sandbox Code Playgroud) 当服务器的内容类型是"Content-Type:text/html"时.requests.get()返回不正确编码的数据.就好像我们将内容类型明确地称为'Content-Type:text/html; charset = utf-8',它返回正确的数据.
当我们使用urllib.urlopen()时,它返回正确的数据.以前有人注意到了吗?为什么requests.get()表现得像这样?
我有 html 文件来读取解析等,它是在 unicode 上编码的(我用记事本看到的)但是当我尝试时
infile = open("path", "r")
infile.read()
Run Code Online (Sandbox Code Playgroud)
它失败了,我遇到了著名的错误:
UnicodeEncodeError: 'charmap' 编解码器无法对位置 xx 中的字符进行编码:字符映射到未定义
因此,为了进行测试,我尝试将文件的包含复制粘贴到一个新文件中并将其保存在 utf-8 中,然后尝试使用这样的编解码器打开它:
inFile = codecs.open("path", "r", encoding="utf-8")
outputStream = inFile.read()
Run Code Online (Sandbox Code Playgroud)
但我收到此错误消息:
UnicodeEncodeError : 'charmap' 编解码器无法对位置 0 的字符 u'\ufeff' 进行编码:字符映射到未定义
我真的不明白,因为我是用 utf8 创建的这个文件。
我正在使用Python和lxml并且遇到了错误
我的代码
>>>import urllib
>>>from lxml import html
>>>response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Grapevine/GrapevineFordLincoln_1/fullservice-505318162.html').read()
>>>dom = html.fromstring(response)
>>>dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='service-review-paragraph loose-spacing']")[0].text_content()
Run Code Online (Sandbox Code Playgroud)
追溯
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/lxml/html/__init__.py", line 249, in text_content
return _collect_string_content(self)
File "xpath.pxi", line 466, in lxml.etree.XPath.__call__ (src/lxml/lxml.etree.c:119105)
File "xpath.pxi", line 242, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:116936)
File "extensions.pxi", line 552, in lxml.etree._unwrapXPathObject (src/lxml/lxml.etree.c:112473)
File "apihelpers.pxi", line 1344, in lxml.etree.funicode (src/lxml/lxml.etree.c:21864)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 477: invalid start byte
Run Code Online (Sandbox Code Playgroud)
问题是我提取的div中存在的特殊字符.如何编码/解码文本而不丢失任何数据?
嘿,我试图将这个小片段从2端口移植到Python 3.
Python 2:
def _download_database(self, url):
try:
with closing(urllib.urlopen(url)) as u:
return StringIO(u.read())
except IOError:
self.__show_exception(sys.exc_info())
return None
Run Code Online (Sandbox Code Playgroud)
Python 3:
def _download_database(self, url):
try:
with closing(urllib.request.urlopen(url)) as u:
response = u.read().decode('utf-8')
return StringIO(response)
except IOError:
self.__show_exception(sys.exc_info())
return None
Run Code Online (Sandbox Code Playgroud)
但我还是得到了
utf-8 codec can't decode byte 0x8f in position 12: invalid start byte
Run Code Online (Sandbox Code Playgroud)
我需要使用StringIO,因为它是一个zipfile,我想用该函数解析它:
def _parse_zip(self, raw_zip):
try:
zip = zipfile.ZipFile(raw_zip)
filelist = map(lambda x: x.filename, zip.filelist)
db_file = 'IpToCountry.csv' if 'IpToCountry.csv' in filelist else filelist[0]
with closing(StringIO(zip.read(db_file))) as raw_database:
return_val …
Run Code Online (Sandbox Code Playgroud) 我使用的是Python 3.x. 在使用urllib.request
下载网页时,我\n
之间的关系很多.我试图使用论坛其他主题中给出的方法删除它,但我无法这样做.我用过strip()
功能和replace()
功能......但没有运气!我在eclipse上运行这段代码.这是我的代码:
import urllib.request
#Downloading entire Web Document
def download_page(a):
opener = urllib.request.FancyURLopener({})
try:
open_url = opener.open(a)
page = str(open_url.read())
return page
except:
return""
raw_html = download_page("http://www.zseries.in")
print("Raw HTML = " + raw_html)
#Remove line breaks
raw_html2 = raw_html.replace('\n', '')
print("Raw HTML2 = " + raw_html2)
Run Code Online (Sandbox Code Playgroud)
我无法发现\n
在raw_html
变量中获得大量内容的原因.