从<a href="" tag="" using="" beautifulsoup=""

时间:2018-11-11 04:08:23

标签: python beautifulsoup

="" I am using BeautifulSoup to extract all the links from this page: http://kern.humdrum.org/search?s=t&keyword=Haydn

中提取特定的页面链接

我通过这种方式获取所有这些链接:

# -*- coding: utf-8 -*-

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'http://kern.humdrum.org/search?s=t&keyword=Haydn'

#opening up connecting, grabbing the page
uClient = uReq(my_url)

# put all the content in a variable
page_html = uClient.read()

#close the internet connection
uClient.close()

#It does my HTML parser
page_soup = soup(page_html, "html.parser")

# Grab all of the links
containers = page_soup.findAll('a', href=True)
#print(type(containers))

for container in containers:
    link = container
    #start_index = link.index('href="') 
    print(link)
    print("---")
    #print(start_index)

我的输出的一部分是: enter image description here

请注意,它正在返回几个链接,但我确实希望所有> Someting链接。 (例如,“> Allegro”和“ Allegro vivace”等)。

我很难获得以下类型的输出(图像示例): “快板-http://kern.ccarh.org/cgi-bin/ksdata?location=users/craig/classical/beethoven/piano/sonata&file=sonata01-1.krn&format=info

换句话说,在这一点上,我有一堆锚标记(+-1000)。从所有这些标签中,有一堆只是“垃圾”,我想提取+-350个标签。所有这些标签看起来几乎相同,但是唯一的区别是我需要的标签的末尾带有“>某人的名字<\ a>”。我只想吸引所有具有此特征的锚标签的链接。

4 个答案:

答案 0 :(得分:3)

从图像中我可以看到,带有信息的信息具有包含href的{​​{1}}属性,因此您可以使用{= {1}}的attribute = value CSS选择器,其中{{ 1}}表示包含;属性值包含第一个等于之后的子字符串。

format="info"

答案 1 :(得分:1)

最好和最简单的方法是在打印链接时使用text属性。像这样 : print link.text

答案 2 :(得分:0)

假设您已经有了需要搜索的子字符串列表,则可以执行以下操作:

for link in containers:
    text = link.get_text().lower()
    if any(text.endswith(substr) for substr in substring_list):
        print(link)
        print('---')

答案 3 :(得分:0)

您要提取具有指定锚文本的链接吗?

for container in containers:
    link = container
    # match exact
    #if 'Allegro di molto' == link.text:
    if 'Allegro' in link.text: # contain
        print(link)
        print("---")
相关问题