2014-10-09 46 views
0

我使用Python 2和美丽的汤解析使用请求模块如何使用美丽的汤从HTML锚标签返回目的地

import requests 
from bs4 import BeautifulSoup 

site = requests.get("http://www.stackoverflow.com/") 
HTML = site.text 
links = BeautifulSoup(HTML).find_all('a') 

返回包含输出,它看起来像<a href="hereorthere.com">Navigate</a>

列表检索到的HTML

每个锚标记的属性href的内容可以有多种形式,例如它可以是页面上的JavaScript调用,它可以是具有相同域(/next/one/file.php)的页面的相对地址,或者它可以是特定的网址(http://www.stackoverflow.com/)。

使用BeautifulSoup有可能将相对和特定地址的网址返回到一个列表,排除所有JavaScript调用等,只留下可导航的链接?

+0

这是你在找什么? :http://stackoverflow.com/questions/9057809/python-module-beautifulsoup-extracting-anchors-href – jmunsch 2014-10-09 18:25:58

回答

0

BS docs

One common task is extracting all the URLs found within a page’s <a> tags: 

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

您可以过滤掉HREF = “JavaScript的:什么()” 的情况下是这样的:

hrefs = [] 
for link in soup.find_all('a'): 
    if link.has_key('href') and not link['href'].lower().startswith('javascript:'): 
     hrefs.append(link['href'])