我有一个代码,这样:
a = "\u0432"
b = u"\u0432"
c = b"\u0432"
d = c.decode('utf8')
print(type(a), a)
print(type(b), b)
print(type(c), c)
print(type(d), d)
Run Code Online (Sandbox Code Playgroud)
并输出:
<class 'str'> ?
<class 'str'> ?
<class 'bytes'> b'\\u0432'
<class 'str'> \u0432
Run Code Online (Sandbox Code Playgroud)
为什么在后一种情况下我看到的是字符代码,而不是字符?我如何将Byte字符串转换为Unicode字符串,在输出的情况下,我看到了字符而不是代码?
我正在尝试向以下页面发出POST请求:http://search.cpsa.ca/PhysicianSearch
为了模拟单击"搜索"按钮而不填写任何表单,这会向页面添加数据.在查看chrome开发人员工具中的网络选项卡时,通过单击按钮获取POST标头信息.我发布这个而不是仅仅从其他类似问题复制解决方案的原因是我相信我可能没有得到正确的标题信息.格式是否正确,我是否抓住了正确的信息?我之前从未发过过POST请求.
这就是我设法拼凑的东西:
import urllib.parse
import urllib.request
data = urllib.parse.urlencode({'Host': 'search.cpsa.ca', 'Connection': 'keep-alive', 'Content-Length': 23796,
'Origin': 'http://search.cpsa.ca', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cahce-Control': 'no-cache', 'X-Requested-With': 'XMLHttpRequest',
'X-MicrosoftAjax': 'Delta=true', 'Accept': '*/*',
'Referer': 'http://search.cpsa.ca/PhysicianSearch',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6',
'Cookie': 'ASP.NET_SessionId=kcwsgio3dchqjmyjtwue402c; _ga=GA1.2.412607756.1459536682; _gat=1'})
url = "http://www.musi-cal.com/cgi-bin/query?%s"
data = data.encode('ascii')
with urllib.request.urlopen("http://search.cpsa.ca/PhysicianSearch", data) as f:
print(f.read().decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
此解决方案输出页面的HTML,但不包含我想要从POST请求中检索的任何数据.
我是新手测试,需要一些帮助.
假设有这种方法:
from urllib.request import urlopen
def get_posts():
with urlopen('some url here') as data:
return json.loads(data.read().decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
问题是如何测试这个方法(如果可能的话,使用mock.patch装饰器)?
我现在拥有的:
@mock.patch('mymodule.urlopen')
def test_get_post(self, mocked_urlopen):
mocked_urlopen.__enter__ = Mock(return_value=self.test_data)
mocked_urlopen.__exit__ = Mock(return_value=False)
...
Run Code Online (Sandbox Code Playgroud)
但它似乎没有奏效.
PS有没有方便的方法在测试中使用数据变量(哪种类型是HTTPResponse),所以它可能只是简单的字符串?
python ×2
python-3.x ×2
http ×1
post ×1
string ×1
testing ×1
unicode ×1
unit-testing ×1
web-scraping ×1