- Python自帶標準庫urllib
#urllib.parse 用于解析url
import urllib.parse
kw={'wd':'*'}
#編碼
result=urllib.parse.urlencode(kw)
print(result)
#解碼
res=urllib.parse.unquote(result)
print(res)
#urllib.request 用于打開和讀取URL
import urllib.request
import urllib.parse
url='*'
headers={'User-Agent':'*'}
data={'username':'*','password':'*','action':'login'}
#1.發(fā)送請求
resp=urllib.request.urlopen(url,data=bytes(urllib.parse.urlencode(data),encoding='utf-8'))
html=resp.read().decode('gbk') #decode將bytes類型轉成str類型
print(html)
#2.構建請求對象
req=urllib.request.Request(url,headers=headers)
#使用urlopen打開請求
resp=urllib.request.urlopen(req)
#從響應結果中讀取數據
html=resp.read().decode('utf-8')
print(html)
#https://www.xicidaili.com/nn/ 用于免費代理IP
from urllib.request import build_opener
from urllib.request import ProxyHandler
proxy=ProxyHandler({'https':'*(IP地址):*(端口號)'})
opener=build_opener(proxy)
url='*'
resp=opener.open(url)
print(resp.read().decode('utf-8'))
#cookie 用于解決http的無狀態(tài)性
import urllib.request
from http import cookiejar
filename='cookie.txt'
#獲取cookie
def get_cookie():
cookie=cookiejar.MozillaCookieJar(filename) #實例化一個MozillaCookieJar 用于保存cookie
handler=urllib.request.HTTPCookieProcessor(cookie) #創(chuàng)建handler對象
opener=urllib.request.build_opener(handler) #創(chuàng)建opener對象
url='*'
resp=opener.open(url) #請求網址
cookie.save() #存儲cookie文件
#讀取cookie
def use_cookie():
cookie=cookiejar.MozillaCookieJar() #實例化MozillaCookieJar
cookie.load(filename) #加載cookie文件
print(cookie)
if __name__=='__main__':
get_cookie()
use_cookie()
#urllib.error.URLError 用于捕獲由urllib.request產生的異常
import urllib.request
import urllib.error
url='*’
try
resp=urllib.request.urlopen(url)
except urllib.error.URLError as e
print(e.reason)
#urllib.error.HTTPError 用于處理HTTP與HTTPS請求的錯誤
import urllib.request
import urllib.error
url='*’
try
resp=urllib.request.urlopen(url)
except urllib.error.HTTPError as e
print('原因:',e.reason)
print('響應狀態(tài)碼:',str(e.code))
print('響應頭數據:',e.headers)
- 第三方requests庫
#requests.get() 用于發(fā)送get請求
import requests
url='*’
params=['*':'*']
resp=requests.get(url,params=params)
resp.encoding='utf-8' #設置響應的編碼格式
cookie=resp.cookies #獲取請求后的cookie信息
headers=resp.headers
print('響應狀態(tài)碼:',resp.status_code)
print('請求后的cookie:',cookie
print('獲取請求的網址:',resp.url)
print('響應頭:',headers)
print('響應內容:',resp.text)
json_data=resp.json() #獲取json數據
print(json_data)
with open('*','wb') as file #存儲二進制數據
file.write(resp.content)
session=requests.session() #使用session
resp=session.get(url)
resp.encoding='utf-8’
print(resp.text)
#requests.post() 用于發(fā)送post請求
import requests
url='*'
data={'username':'*','password':'*','action':'login'}
resp=requests.post(url,data=data)
resp.encoding='gb2312’
print(resp.status_code)
print(resp.text)
session=requests.session() #使用session
resp=session.post(url,data=data)
resp.encoding='gb2312’
print(resp.text)
- 第三方庫XPath
#XPath 用于提取數據
import requests
from lxml import etree
url='*'
headers={'User-Agent':'*'}
resp=requests.get(url,headers) #發(fā)送請求
e=etree.HTML(resp.text) #將str類型轉換成class 'lxml.etree._Element'(print(type(e)))
e1=e.xpath('//*節(jié)點名[last()-1]/text()')
e2=e.xpath('//*節(jié)點名[@*屬性="*"]/text()')
for e1,e2 in zip(e1,e2)
print(e1,":",e2)
- 第三方庫BeautifulSoup
#BeautifulSoup 用于提取數據
from bs4 import BeautifulSoup
html='''
<html>
<head>
<title>*</title>
</head>
<body>
<h1 class='*'>*</h1>
</body>
</html>
'''
bs=BeautifulSoup(html,'html.parser')
bs=BeautifulSoup(html,'lxml')
print(bs.title) #獲取標簽
print(bs.h1.attrs) #獲取h1標簽的所有屬性
#獲取單個屬性
print(bs.h1.get('class'))
print(bs.h1['class'])
#獲取文本內容
print(bs.title.text)
print(bs.title.string) #獲取包括注釋內容
print(bs.find('h1',class_='*')) #獲取第一個滿足條件的標簽
print(bs.find_all('h1',class_='*')) #獲取所有滿足條件的標簽列表
for item in bs.find_all('h1',class_='*')
print(item)
print(bs.find_all('h1',attrs={'class':'*'}))
#css選擇器
print(bs.select("#*"))
print(bs.select('.*'))
print(bs.select('*>*'))
print(bs.select('*.*>*'))
for item in bs.select('*.*>*'):
print(item.text)