如何使用 Beautifulsoup 查找所有“href”属性
有关如何提取所有 URL 元素的分步指南。
重要提示:我们将在本教程中使用真实示例,因此您需要安装请求和 Beautifulsoup 库。
步骤 1。 让我们首先导入 Beautifulsoup 库。
from bs4 import BeautifulSoup
步骤 2。 然后,导入请求库。
import requests
步骤 3。 获取目标登录页面的源代码。我们将在此示例中使用主页。
r=requests.get("https://proxyway.com/")
通用代码可能如下所示:
r=requests.get("Your URL")
步骤 4。 将 HTML 代码解析为名为的 Beautifulsoup 对象 汤.
soup=BeautifulSoup(r.content,"html.parser")
步骤 5。 然后,找到所有链接 HREF 属性。我们将使用此标签作为示例:
link_elements = soup.find_all("a", href=True)
注意: 您还可以指定一个类别。
link_elements = soup.find_all("a", class_=”some_class”, href=True)
步骤 6。 将您找到的所有链接放入字典中以便跟踪它们。
dict_of_links = {}
注意: 该链接将被分配给在 a 标签。
步骤 7。 如果某个元素存在字符串,则可以遍历所有 链接元素 你已经把它们抓取并放入字典中。
for element in link_elements: if element.string: dict_of_links[element.string] = element['href']
步骤 8。 让我们通过打印来检查我们的代码是否有效。
print (dict_of_links)
结果:
恭喜,您已提取所有 URL。以下是完整脚本:
from bs4 import BeautifulSoup
import requests
r = requests.get("https://proxyway.com")
soup = BeautifulSoup(r.content, "html.parser")
link_elements = soup.find_all("a", href=True)
dict_of_links = {}
for element in link_elements:
if element.string:
dict_of_links[element.string] = element['href']
print (dict_of_links)