TShopping

 找回密碼
 註冊
搜索
查看: 10085|回復: 0
打印 上一主題 下一主題

[教學] python 利用 BeautifulSoup4 網路爬蟲抓網頁標題

[複製鏈接]
跳轉到指定樓層
1#
發表於 2020-10-8 15:41:05 | 只看該作者 |只看大圖 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook
演示圖



首先用終端機安裝BeautifulSoup 4模組
  1. pip install beautifulsoup4
複製代碼

anaconda
  1. conda install beautifulsoup4
複製代碼


以PTT 八卦版為例
完整原始碼
  1. import urllib.request as req
  2. def getData(url):
  3.     request=req.Request(url,headers={
  4.     "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
  5.     ,"cookie":"over18=1"
  6.     })
  7.     with req.urlopen(request) as response:
  8.         data=response.read().decode("utf-8") #utf-8編碼
  9.     #print(data)
  10.     # conda install beautifulsoup4
  11.     # 解析原始碼,抓取文章標題
  12.     import bs4
  13.     root = bs4.BeautifulSoup(data,"html.parser") #html 格式
  14.     titles=root.find_all("div",class_="title") #find all class="title" 的div標籤
  15.     #print(titles)
  16.     for title in titles:
  17.         if title.a != None: #如果標題包含 a 標籤(沒有被刪除),就印出來
  18.             print(title.a.string)

  19.     nextLink = root.find("a",string="‹ 上頁") #找到內文是 ‹ 上頁 的 a 標籤
  20.     #print(nextLink["href"])
  21.     return nextLink["href"]

  22. #主程序:抓取5個頁面標題
  23. pageURL = "https://www.ptt.cc/bbs/Gossiping/index.html" #抓取網址
  24. count=0
  25. while count<5:  #抓取5頁
  26.     pageURL = "https://www.ptt.cc"+getData(pageURL)
  27.     count+=1
  28. # print(pageURL)
複製代碼

解說:
以下這段在模擬用戶用瀏覽器上網,"cookie":"over18=1" 是已點選 我滿18歲的紀錄
  1. request=req.Request(url,headers={
  2. "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
  3. ,"cookie":"over18=1"
  4. })
複製代碼

可在chrome瀏覽器壓F12或開發者模式看到
選取Application


網頁設計,網站架設 ,網路行銷,網頁優化,SEO - NetYea 網頁設計

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-27 06:08 , Processed in 0.085065 second(s), 25 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表