爬取有道,一开始运行以下代码出现了AttributeError: module ‘urllib.request’ has no attribute 'parse’的问题
from urllib import request
#import urllib.request as request
import urllib.parse
...
...
...
```python
data = request.parse.urlencode(formdata).encode(encoding='utf-8')
后来百度才知道request已经不是一个方法而是一个模块了,所以我们必须用导入模块的方法进行导入,
import urllib.request as request
而且parse是urllib里面的一个方法,所以直接urllib.parse就可以调用parse了。
下面直接附上正确的代码
import urllib.request as request#request作为模块导入
import urlli
header = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"}
key = input("请输入需要翻译的文字:")
fromdata={
"action":"FY_BY_REALTlME",
"bv":"908078567e4fa99e9a8b55bb7ca876a4",
"client":"fanyideskweb",
"doctype":"json",
"from":"AUTO",
"i":key,
"keyfrom":"fanyi.web",
"salt":15840040561109,
"sign":"28e7538ef947d7a398362bb9572267d5",
"smartresult":"dict",
"to":"AUTO",
"ts":"1584004056110",
"version":"2.1",
}
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
#经过urlencode()对key转码
data = urllib.parse.urlencode(fromdata).encode(encoding="utf-8")
req = request.Request(url,data=data,headers= header)
response=request.urlopen(req).read()
print(response)