【问题标题】:Creating a unique list with beautiful soup from href attribute Python从 href 属性 Python 创建一个带有漂亮汤的唯一列表
【发布时间】:2017-01-18 14:57:41
【问题描述】:

我正在尝试为我的锚标签上的所有 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 循环中,但这并没有改变我的结果。

【问题讨论】:

    标签: python beautifulsoup unique href


    【解决方案1】:

    首先,您不能就地调用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
    

    【讨论】:

    • @BatsAuto 如果这解决了您的问题,请将其标记为正确。否则,如果您还想做其他事情,请在这些 cmets 中告诉我。
    • 为什么不只是href_set = {tag.get('href') for tag in tags}
    • 我试图说明使用 set() 来转换列表,这是 OP 试图做的。不过,我可以将集合理解添加到答案中。
    • 当然,但他们也可以一步一步学习,从他们未能分配集合调用的结果来判断,我想他们可能不知道你可以一次完成步骤。
    • 我同意知道这一点很好,但他们最好先了解基础知识,然后再担心优化。
    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2013-04-12
    • 2019-11-06
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多