为了账号安全,请及时绑定邮箱和手机立即绑定

python3中的urllib

#python3的urllib2和urllib合并了
#import urllib2会报错
import urllib.request
#直接请求
response = urllib.request('http://www.baidu.com')
#获取状态码,如果是200表示成功
print(response.getcode())
#读取内容
cont=response.read()

报错'module' object is not callable

换成

response = urllib.request.Request('http://www.baidu.com')

报错 'Request' object has no attribute 'getcode'


https://www.jianshu.com/p/1c10e6b36dd4


正在回答

2 回答

url = "https://wwww.baidu.com/"
response = request.urlopen(url)
print(response.getcode())
print(response.read())
应该用urlopen方法
request.Request是构建一个完整的请求:
    req = urllib.request.Request(url)
    response = urllib.request.urlopen(req)
    #用Request类构建了一个完整的请求,增加了headers等一些信息
    
 详细内容可参考request源码


1 回复 有任何疑惑可以回复我~
#1

一个大憨憨

是的,如果如果你把import urllib.request换成from urllib import request,后面代码中的urllib.request可以直接用request代替
2020-03-09 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Python开发简单爬虫
  • 参与学习       227734    人
  • 解答问题       1218    个

本教程带您解开python爬虫这门神奇技术的面纱

进入课程

python3中的urllib

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信