如何獲取一個頁面內所有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=https://www.cnblogs.com/chengxuyuanaa/p/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交流.裙 :七衣衣九七七巴而五(數字的諧音)轉換下可以找到了,還可以跟老司機交流討教!
本文的文字及圖片來源于網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/140874.html
標籤:Python
