利用urllib进行简单的网页抓取
1直接代码
from urllib import request if __name__ == "__main__": response = request.urlopen("http://fanyi.baidu.com") html = response.read() # 必须解码,参数页面编码很重要 html = html.decode("utf-8") print(html)
2获取网页编码的方式
有很多,推荐一种最方便的,安装第三方库chardet,它是用来判断编码的模块,安装方法cmd->输入指令:
pip install chardet
然后就可以代码实现了:
from urllib import request import chardet if __name__ == "__main__": response = request.urlopen("http://fanyi.baidu.com/") html = response.read() charset = chardet.detect(html) print(charset) # 获取编码 print(charset["encoding"])

浙公网安备 33010602011771号