標籤:chrome瀏覽器 htm 代碼 ret set attr 函數 params ima
安裝BeautifulSoup以及requests
開啟window 的cmd視窗輸入命令pip install requests 執行安裝,等待他安裝完成就可以了
BeautifulSoup庫也是同樣的方法
我使用的編譯器的是sublime text 3,覺得是挺好用的一個編譯軟體
其他工具: Chrome瀏覽器
Python版本: Python3.6
運行平台: Windows
1、首先我們搜尋OA幸運飛艇平台熱門排行榜:【×××。com/h5】企 娥:217 1793 408
擷取網頁的代碼:
[python] view plain copy
def getHTMLText(url,k):
try:
if(k==0):
a={}
else:
a={‘offset‘:k}
r = requests.get(url,params=a,headers={‘User-Agent‘: ‘Mozilla/4.0‘})
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
print("Failed!")
經過觀察其中因為每一頁的網址其offset都不相同,故只要改變offset=k便可擷取每一頁的資訊
通過main函數以改變URL:
[python] view plain copy
def main():
basicurl=‘×××。com/h5‘
k=0
while k<=100:
html=getHTMLText(basicurl,k)
k+=10
getname(html)
通過BeautifulSoup的方法層層擷取標籤中的資訊,並for迴圈輸出
[python] view plain copy
def getname(html):
soup = BeautifulSoup(html, "html.parser")
paihangList=soup.find(‘dl‘,attrs={‘class‘:‘board-wrapper‘})
mov=[]
actor=[]
for movlist in paihangList.find_all(‘dd‘):
movitem=movlist.find(‘div‘,attrs={‘class‘:‘movie-item-info‘})
movname=movitem.find(‘p‘,attrs={‘class‘:‘name‘}).getText()
actors=movlist.find(‘div‘,attrs={‘class‘:‘board-item-main‘})
actorname=actors.find(‘p‘,attrs={‘class‘:‘star‘}).getText()
b=actorname.replace(‘\n‘,‘‘)
c=b.replace(‘ ‘,‘‘)
actor.append(c)
mov.append(movname)
mode= "{0:<30}\t{1:<50}"
for i,j in zip(mov,actor):
print(mode.format(i,j,chr(12288)))
Python爬蟲爬取OA幸運飛艇平台擷取資料