从 href 属性 Python 创建一个带有漂亮汤的独特列表

Creating a unique list with beautiful soup from href attribute Python

我正在尝试为我的锚标签上的所有 href 创建一个唯一列表

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/

我试过将 set(tag) 移动到 for 循环中,但这并没有改变我的结果。

首先,你不能原地调用set(),它是returns一个值的转换。

tag_set = set(tags)

其次,set不一定理解BeautifulSoup中Tag对象的区别。就其而言,在 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