日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python中的urllib,urllib三种不同的请求方式

發布時間:2024/9/27 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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三种不同的请求方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。