从页面获取所有链接美丽的汤

use*_*364 8 python beautifulsoup html-parsing web-scraping

我正在使用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')
Run Code Online (Sandbox Code Playgroud)

我得到的只是:

[]
Run Code Online (Sandbox Code Playgroud)

如何获取该页面上所有href链接的列表?

Ano*_*nta 13

你告诉find_all方法找到href标签,而不是属性.

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

links = soup.find_all('a')
Run Code Online (Sandbox Code Playgroud)

稍后你可以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
Run Code Online (Sandbox Code Playgroud)


小智 9

替换你的最后一行:

links = soup.find_all('a')
Run Code Online (Sandbox Code Playgroud)

按行:

links = [a.get('href') for a in soup.find_all('a', href=True)]
Run Code Online (Sandbox Code Playgroud)

它将废弃所有a标记,并且对于每个a标记,它会将该href属性附加到链接列表.

如果您想了解更多关于for循环的信息[],请阅读有关List comprehensions的内容.