Python爬蟲如何獲取頁面內所有URL鏈接?本文詳解


 

如何獲取一個頁面內所有URL鏈接?在Python中可以使用urllib對網頁進行爬取,然后利用Beautiful Soup對爬取的頁面進行解析,提取出所有的URL。

什么是Beautiful Soup?

Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數據,因為簡單,所以不需要多少代碼就可以寫出一個完整的應用程序。

Beautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。

BeautifulSoup支持Python標准庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更加強大,速度更快。

全部代碼:

from bs4 import BeautifulSoup
import time,re,urllib2
t=time.time()
websiteurls={}
def scanpage(url):
  websiteurl=url
  t=time.time()
  n=0
  html=urllib2.urlopen(websiteurl).read()
  soup=BeautifulSoup(html)
  pageurls=[]
  Upageurls={}
  pageurls=soup.find_all("a",href=True)
  for links in pageurls:
    if websiteurl in links.get("href") and links.get("href") not in Upageurls and links.get("href") not in websiteurls:
      Upageurls[links.get("href")]=0
  for links in Upageurls.keys():
    try:
      urllib2.urlopen(links).getcode()
    except:
      print "connect failed"
    else:
      t2=time.time()
      Upageurls[links]=urllib2.urlopen(links).getcode()
      print n,
      print links,
      print Upageurls[links]
      t1=time.time()
      print t1-t2
    n+=1
  print ("total is "+repr(n)+" links")
  print time.time()-t
scanpage("http://news.163.com/")

利用BeautifulSoup還可以有針對性的獲取網頁鏈接:Python爬蟲獲取網頁上的鏈接,通過beautifulsoup的findall()方法對匹配的標簽進行查找。
最后注意:光理論是不夠的。這里順便送大家一套2020最新python入門到高級項目實戰視頻教程,可以去小編的Python交流.裙 :七衣衣九七七巴而五(數字的諧音)轉換下可以找到了,還可以跟老司機交流討教!

本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM