【问题标题】:Get the title of a link using BeautifulSoup使用 BeautifulSoup 获取链接的标题
【发布时间】:2017-08-04 05:57:41
【问题描述】:

正如标题所说,我正在尝试获取位于单元格内的链接的标题。 This is 我从中获取资料的网站。我还看到了this 问题,这是我最后几行代码的来源,但对我来说并没有完成

我正在尝试获取第一列(或每行的第一个单元格)内的链接标题。我可以在单元格中获取 所有 的 HTML 代码,但我无法确定仅获取标题。到目前为止,这是我想出的

URL = 'http://theescapists.gamepedia.com/Crafting'
get_page = requests.get(URL)
plain_text = get_page.text
soup = BeautifulSoup(plain_text, 'html.parser')


for table_tag in soup.find_all('table'):
    for each_row in table_tag.find_all('tr'):
        links = each_row.find('a', href=True)
        title = links.get('title')
        print(title)
        print('')

如果我只打印links 部分,每个单元格中的所有代码都会被打印出来。

当我打印title 部分时,我收到一条错误消息AttributeError: 'NoneType' object has no attribute 'get',这让我很困惑,因为我已经完成了print(type(links)) and I get abs4.element.Tagback, which makes me think I should be able to look through for atitle` 标签。

作为回顾(这似乎有点长),我想从每个表中每个链接的 第一个单元格中获取标题标签

【问题讨论】:

    标签: html python-3.x beautifulsoup


    【解决方案1】:

    我认为links.attrs['title'] 是你想要的。

    我的代码:

    for table_tag in soup.find_all('table'):
        for each_row in table_tag.find_all('tr'):
            links = each_row.find('a', href=True)
            try:
                title = links.attrs['title']
                print(title)
                print('')
            except AttributeError:
                pass
    

    注意:AttributeError 将处理没有title 的表头。

    【讨论】:

      【解决方案2】:

      tr标签可以包含th标签而没有a标签,你应该在访问之前检查a标签:

      In [100]: for table_tag in soup.find_all('table'):
           ...:     for each_row in table_tag.find_all('tr'):
           ...:         links = each_row.find('a', href=True)
           ...:         if links: # check before you access
           ...:             title = links.get('title')
           ...:             print(title)
           ...:             print('')
      

      【讨论】:

        猜你喜欢
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        • 2018-06-18
        • 2020-01-23
        • 1970-01-01
        • 2020-12-19
        • 1970-01-01
        • 2012-10-10
        相关资源
        最近更新 更多