如何仅从与类匹配的 anchor 标记中的 href 中获取文本。所以如果我有
<a href="Link_I_Need.html" class="Unique_Class_Name">link text</a>
如何仅从具有 Unique_Class_Name 类的 anchor 标记中获取字符串 Link_I_Need.html?
最佳答案
使用 .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'])
您也可以使用带有 .select()
method 的基本 CSS 选择器:
soup = BeautifulSoup(html)
for anchor in soup.select('a.Unique_Class_Name'):
if anchor.has_attr('href'):
print (anchor['href'])
关于python - 在 Python 中使用 BeautifulSoup 获取具有特定类属性的链接的 href 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416575/