python爬虫获取url_Python爬虫如何获取页面内所有URL链接?本文详解
如何獲取一個頁面內(nèi)所有URL鏈接?在Python中可以使用urllib對網(wǎng)頁進(jìn)行爬取,然后利用Beautiful Soup對爬取的頁面進(jìn)行解析,提取出所有的URL。
什么是Beautiful Soup?
Beautiful Soup提供一些簡單的、python式的函數(shù)用來處理導(dǎo)航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數(shù)據(jù),因?yàn)楹唵?#xff0c;所以不需要多少代碼就可以寫出一個完整的應(yīng)用程序。
Beautiful Soup自動將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。
BeautifulSoup支持Python標(biāo)準(zhǔn)庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python默認(rèn)的解析器,lxml 解析器更加強(qiáng)大,速度更快。
全部代碼:
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還可以有針對性的獲取網(wǎng)頁鏈接:Python爬蟲獲取網(wǎng)頁上的鏈接,通過beautifulsoup的findall()方法對匹配的標(biāo)簽進(jìn)行查找。
最后注意:光理論是不夠的。這里順便送大家一套2020最新python入門到高級項(xiàng)目實(shí)戰(zhàn)視頻教程,可以去小編的Python交流.裙 :七衣衣九七七巴而五(數(shù)字的諧音)轉(zhuǎn)換下可以找到了,還可以跟老司機(jī)交流討教!
本文的文字及圖片來源于網(wǎng)絡(luò)加上自己的想法,僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,版權(quán)歸原作者所有,如有問題請及時聯(lián)系我們以作處理。
總結(jié)
以上是生活随笔為你收集整理的python爬虫获取url_Python爬虫如何获取页面内所有URL链接?本文详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python如何使用字典_Python-
- 下一篇: python包和目录有什么不同_pyth