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

标签 python beautifulsoup unique href

我正在尝试为我的 anchor 标签上的所有 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(),它是一个返回值的转换。

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

关于python - 从 href 属性 Python 创建一个带有漂亮汤的独特列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39428834/

相关文章:

c# - 提取网格或点云的中心曲线(中轴或拓扑骨架)的代码?

python - 将 URL 作为 Django URL 中的参数传递

python - 如何从 python 列表中的元素中提取 float ?

Redis:过期集元素 - 成员必须是唯一的

python - pandas 列中唯一值的返回顺序

python - 如何检测 firebase firestore 数据库中的实时监听器错误?

python - 创建与 'clam' ttk 主题相同的自定义 ttk 样式(特定于按钮小部件)

python - 如何使用Python在BeautifulSoup中提取同一div中具有相同标签的元素?

python - 解析 URL beautifulsoup

python - 如何按唯一值分组 pandas groupby