Python爬蟲獲取頁面所有URL鏈接過程詳解
如何獲取一個頁面內所有URL鏈接?在Python中可以使用urllib對網頁進行爬取,然后利用Beautiful Soup對爬取的頁面進行解析,提取出所有的URL。
什么是Beautiful Soup?
Beautiful Soup提供一些簡單的、python式的函數(shù)用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數(shù)據,因為簡單,所以不需要多少代碼就可以寫出一個完整的應用程序。
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()方法對匹配的標簽進行查找。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)將Excel轉換成為image的方法
今天小編就為大家分享一篇Python實現(xiàn)將Excel轉換成為image的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
python如何解析復雜sql,實現(xiàn)數(shù)據庫和表的提取的實例剖析
這篇文章主要介紹了python如何解析復雜sql,實現(xiàn)數(shù)據庫和表的提取的實例剖析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

