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

标签 python html python-2.7 web-scraping beautifulsoup

如何仅从与类匹配的 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/

相关文章:

php - 水平获取数据到html表格中

javascript - jquery load() 特定 div 不起作用

python-2.7 - 尝试安装pycurl时出错

python - 谷歌应用程序引擎启动器上的应用程序错误

python - Python 2.7.6 中是否有 EXIT_SUCCESS 和 EXIT_FAILURE 宏的类似物

python - 使用 for 循环求未知变量的平方

python - Casper Python 脚本失败,错误代码为 `/usr/bin/python`,但不是 `python`

javascript - 在 HTML5 Canvas 上渲染网格

python - Pandas 将重复行复制为唯一行

python - 将嵌套的 JSON 结构反序列化为 Django 模型对象