2016-09-10 33 views
1

我想箱子所有的HREFs獨特的名單上我的錨標記唯一列表創建與href屬性美麗的湯的Python

from urllib2 import urlopen 

from bs4 import BeautifulSoup 

import pprint 

url = 'http://barrowslandscaping.com/' 

soup = BeautifulSoup(urlopen(url), "html.parser") 
print soup 

tag = soup.find_all('a', {"href": True}) 
set(tag) 
for tags in tag: 
    print tags.get('href') 

結果:

http://barrowslandscaping.com/ 
http://barrowslandscaping.com/services/ 
http://barrowslandscaping.com/design-consultation/ 
http://barrowslandscaping.com/hydroseeding-sodding/ 
http://barrowslandscaping.com/landscape-installation/ 
http://barrowslandscaping.com/full-service-maintenance/ 
http://barrowslandscaping.com/portfolio/ 
http://barrowslandscaping.com/about-us/ 
http://barrowslandscaping.com/contact/ 
http://barrowslandscaping.com/design-consultation/ 
http://barrowslandscaping.com/full-service-maintenance/ 

我已經試過移動設置(標籤)到for循環,但沒有改變我的結果。

回答

4

首先,您不能撥打電話set(),這是一個返回值的轉換。

tag_set = set(tags) 

其次,set不一定了解BeautifulSoup標籤對象之間的差異。就它而言,在HTML中找到了兩個單獨的標籤,因此它們不是唯一的,並且都應該保留在該集合中。它不知道它們具有相同的href值。相反,你應該首先將href屬性提取到一個列表中,然後將它們轉換爲一組。

tags = soup.find_all('a', {"href": True}) 
# extract the href values to a new array using a list comprehension 
hrefs = [tag.get('href') for tag in tags] 
href_set = set(hrefs) 

for href in href_set: 
    print href 

這可以通過使用一組的理解進一步簡化:

tags = soup.find_all('a', {"href": True}) 
href_set = {tag.get('href') for tag in tags} 

for href in href_set: 
    print href 
+0

@BatsAuto如果問題得以解決,標誌着它是正確的。否則,請在這些評論中告訴我是否有其他事情要做。 – Soviut

+0

爲什麼不只是標籤中的'href_set = {tag.get('href')標籤}'? –

+0

我試圖說明使用'set()'來轉換列表,OP正在嘗試做。儘管我可以將集合理解添加到答案中。 – Soviut