【问题标题】:Beautifulsoup: how to get certain link from list?Beautifulsoup:如何从列表中获取某些链接?
【发布时间】:2021-02-24 20:38:44
【问题描述】:

如何使用 BeautifulSoup 从网页中获取链接,将它们存储在列表中,然后打印出某个链接? 这是我目前所拥有的:

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://example.com/")
content = BeautifulSoup(html.read(), "html.parser")
for link in content.find_all("a"):
    print(link.get("href")[0])

但我收到此错误: TypeError: 'NoneType' object is not subscriptable如何解决这个问题并获得第一个链接?

【问题讨论】:

    标签: python python-3.x list web-scraping


    【解决方案1】:

    要检索页面中的所有链接,请使用正则表达式。

    下面的代码应该会为你做:

    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    import re
    
    html = urlopen("https://www.stmaryottumwa.org/")
    content = BeautifulSoup(html.read(), "html.parser")
    links = []
    
    for link in content.find_all("a", attrs={'href': re.compile("^http")}):
        links.append(link.get("href"))
    
    print(links[0]) # print first link on page
    

    可变链接将包含页面上的所有链接。

    【讨论】:

    • 该列表包含链接中的每个字母。不是每个链接。当我执行[0] 时,它返回h,当我执行[1] 时,它返回t,当我执行[2] 时,它返回t,等等。如何解决此问题以便打印整个链接?
    • 如果要打印第一个链接,把最后一行改成print(links[0])
    【解决方案2】:

    为了获取元素的属性,您需要访问.attrs 字典。 还要记住,有时a 标签根本没有href 属性,您可以使用.get 来解决这个问题:

    link.attrs.get('href')
    

    我不确定您希望[0] 做什么,因为a 标记只能有一个href 属性。使用[0] 将获得href 属性的第一个字符

    for link in content.find_all("a"):
        href = a.attrs.get('href')
        if href:
            print(href[0])
    

    【讨论】:

    • print(link.attrs['href'][0]) 返回KeyError: 'href' 错误。有什么想法吗?
    • a标签没有href属性时会发生这种情况,你可以使用try/except块解决它
    • @DeepSpace 好的,但现在我得到了这个:print(link.attrs.get('href', '')[1]) IndexError: string index out of range,当我这样做时print(link.attrs.get('href', '')[0])
    • @Alen 再看一遍......您需要在检查第一个字符之前确保它确实存在。但同样,我不确定你为什么要这样做。如果您想要整个链接,只需print(href)
    • @DeepSpace 我想获得第一个链接。我以为[0] 会这样做
    猜你喜欢
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    相关资源
    最近更新 更多