2017-09-29 95 views
0

我正在使用beautifulsoup获取页面中的所有链接。我的代码是:从页面获取所有链接美丽的汤

import requests 
from bs4 import BeautifulSoup 


url = 'http://www.acontecaeventos.com.br/marketing-promocional-sao-paulo' 
r = requests.get(url) 
html_content = r.text 
soup = BeautifulSoup(html_content, 'lxml') 

soup.find_all('href') 

所有我得到的是:

[] 

我怎样才能得到该网页上的所有HREF链接的列表?

回答

2

您正在通过find_all方法查找href标签,不是属性。

您需要找到<a>标签,它们用于表示链接元素。

links = soup.find_all('a') 

稍后,您可以访问他们的href属性是这样的:

link = links[0]   # get the first link in the entire page 
url = link['href']  # get value of the href attribute 
url = link.get('href') # or like this 
+0

但是当我这样做,我只是得到第一个链接: http://www.acontecaeventos.com.br/ 我应该做一个for循环,让他们都? – user1922364

+0

'links = soup.find_all('a')'给你一个所有链接的列表。我在答案的底部代码中使用了第一个链接作为示例。是的,循环链接列表来访问所有找到的链接。 – Anonta

0

更换你的最后一行:

links = soup.find_all('a') 

通过该行:

links = [a.get('href') for a in soup.find_all('a', href=True)] 

将报废所有的a标签,并且对于每个a标签,它会将href属性附加到链接列表。

如果您想了解更多关于[]之间的for循环,请阅读List comprehensions