简体   繁体   English

Beautifulsoup 如何选择所有的“a”标签

[英]Beautifulsoup how to select all the 'a' tags

I am a newbie to BeautifulSoup and Python.我是 BeautifulSoup 和 Python 的新手。 Here is my HTML:这是我的 HTML:

<html>
<head></head>
<body>
<a href="https://google.com">Google</a>
<a href="https://yahoo.com">Yahoo</a>
</body>
</html>

Now my code:现在我的代码:

from bs4 import BeautifulSoup

# Getting page souped inside Requests, this part is not necessary 

soup = BeautifulSoup(html,'html.parser')
print(soup.find('a'))

This is giving just one link, but I want to get all.这仅提供一个链接,但我想获得所有链接。

Thanks in advance提前致谢

You are using .find() , that will only return the first found, then you have to use .find_all() instead to get a list of the a tags.您正在使用.find() ,它只会返回第一个找到的,然后您必须使用.find_all()来获取 a 标签的列表。

print(soup.find_all('a'))

To get href's by for loop:要通过 for 循环获取 href :

for link in soup.find_all('a'):
  print(link.href)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM