Python中的urllib,urllib三种不同的请求方式
生活随笔
收集整理的這篇文章主要介紹了
Python中的urllib,urllib三种不同的请求方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、urllib獲取服務器的資源
自定義爬蟲的重要組件
獲取百度首頁的資源:
#3.x的標準寫法 import urllib.request import urllib.parse#百度的首頁 from bs4 import BeautifulSoupurl = "http://www.baidu.com/" #發起一個request請求,得到返回對象 res = urllib.request.urlopen(url) #查看http訪問狀態 if res.status == 200:print("訪問成功")#獲取數據data = res.read().decode("utf-8")print(data)soup = BeautifulSoup(data)print(soup.title.string)2.urllib.request回顧
urllib.request提供三種不同的請求方式:
第一種是get請求方式一:urllib.request.urlopen(url)方式二:先創建一個urllib.request.Request對象,然后將對象放入urlopen中。urllib.request.urlopen(Request對象) 第二種是POST:攜帶數據過去比如:登錄用戶名,密碼先創建一個urllib.request.Request將請求數據放到Request對象中urllib.request.Request(url,data)注意:在此之前先將data進行轉化:data = urllib.parse.urlencode(values) 第三種是:添加請求頭 #get 請求 import urllib.request#get 請求方式1 url = "http://www.baidu.com" resp = urllib.request.urlopen(url) if resp.status ==200:data = resp.read().decode("utf-8")#print(data)#get請求方式2 url = "http://www.baidu.com" req = urllib.request.Request(url) resp = urllib.request.urlopen(req) if resp.status ==200:data = resp.read().decode("utf-8")#print(data)#post請求 data = {"name":"張三","age":"17"} url = "http://www.baidu.com" z_data = urllib.parse.urlencode(data) req = urllib.request.Request(url,z_data.encode('utf-8')) resp = urllib.request.urlopen(req) if resp.status ==200:data = resp.read().decode("utf-8")#print(data)#header import urllib.parse import urllib.requesturl = "http://www.baidu.com" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {'name' : 'Michael Foord','location' : 'Northampton','language' : 'Python'} headers = {'User-Agent':user_agent}data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data.encode("utf-8"), headers) response = urllib.request.urlopen(req) the_page = response.read().decode("utf-8") print(the_page)總結
以上是生活随笔為你收集整理的Python中的urllib,urllib三种不同的请求方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黄豆粉猫娘是哪部动漫里的?
- 下一篇: Python邮件发送案例