使用Python中的BeautifulSoup获取具有特定类属性的链接的href文本

dds*_*itz 5 html python beautifulsoup web-scraping python-2.7

如何仅从与类匹配的定位标记中的href中获取文本。所以如果我有

<a href="Link_I_Need.html" class="Unique_Class_Name">link text</a>
Run Code Online (Sandbox Code Playgroud)

如何仅从带有类Unique_Class_Name的锚标记中获取字符串Link_I_Need.html?

Jos*_*ier 5

使用.find().find_all()方法,以选择一个href属性和一个类属性为的元素Unique_Class_Name。然后遍历元素并访问href属性值:

soup = BeautifulSoup(html)
anchors = soup.find_all('a', {'class': 'Unique_Class_Name', 'href': True})

for anchor in anchors:
    print (anchor['href'])
Run Code Online (Sandbox Code Playgroud)

你可以选择使用同一个基本的CSS选择器.select()的方法

soup = BeautifulSoup(html)

for anchor in soup.select('a.Unique_Class_Name'):
    if anchor.has_attr('href'):
        print (anchor['href'])
Run Code Online (Sandbox Code Playgroud)