如何使用 Beautiful Soup 获取“a”元素的“href”属性
有关如何从 一个元素。
重要提示:我们将在本教程中使用真实示例,因此您需要 要求 和 美汤 已安装库。
步骤 1。 让我们首先导入 Beautifulsoup 库。
from bs4 import BeautifulSoup
步骤 2。 然后,导入请求库。
import requests
步骤 3。 获取目标着陆页的源代码。我们将使用 Decodo (以前 Smartproxy) 本示例中的页面。
r=requests.get("https://proxyway.com/reviews/smartproxy-proxies")
普遍适用的代码如下所示:
r=requests.get("Your URL")
步骤 4。 将 HTML 代码转换为名为的 Beautifulsoup 对象 汤.
soup=BeautifulSoup(r.content,"html.parser")
步骤 5。 然后,找到 HREF 您要提取的属性。我们将使用此标签作为示例:
a_href=soup.find("a",{"class":"single-intro__cta"}).get("href")
普遍适用的代码如下所示:
a_href=soup.find("a",{"class":" class of your target a element"}).get("href")
步骤 6。 让我们通过打印来检查我们的代码是否有效。
print(a_href)
结果:
恭喜,您已从 a 元素。以下是完整脚本:
from bs4 import BeautifulSoup
import requests
r=requests.get("https://proxyway.com/reviews/smartproxy-proxies")
soup=BeautifulSoup(r.content,"html.parser")
a_href=soup.find("a",{"class":"single-intro__cta"}).get("href")
print(a_href)