标签:utf python request 爬虫 urllib urlopen print response
1 import urllib.request 2 #获取一个get请求 3 response = urllib.request.urlopen("http://www.baidu.com")
打开网页并返回网页内容给response
print(response.read().decode('utf-8')) #对获取到的网页进行utf-8解码
用于测试HTTP/HTTPS请求的网站
1 #获取一个post请求 2 3 import urllib.parse 4 data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8") 5 response = urllib.request.urlopen("http://httpbin.org/post",data= data) 6 print(response.read().decode("utf-8"))
#获取一个get请求 import urllib.parse response = urllib.request.urlopen("http://httpbin.org/get") print(response.read().decode("utf-8"))
如果访问超时,或者对方网页不予返回信息,(防止程序卡死)应该如何处理。
#超时处理 try: response = urllib.request.urlopen("http://httpbin.org/get", timeout=10)
print(response.read().decode("utf-8")) #对网页信息进行utf-8解码
except urllib.error.URLError as e:
print("time out!")
简单解析网页信息
response = urllib.request.urlopen("http://www.baidu.com") print(response.status) #查看状态信息(200/404/500/418) print(response.getheaders())#查看Response Headers中的信息 print(response.getheader("Server"))#查看Response Headers中的Server属性值(查看单一属性值)
将爬虫伪装成浏览器,以避免被网站识破,返回418信息。
标签:utf,python,request,爬虫,urllib,urlopen,print,response 来源: https://www.cnblogs.com/liweikuan/p/14728200.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。