尝试使用BeautifulSoup从网页中获取绝对链接

时间:2010-03-23 17:22:53

标签: python beautifulsoup

我正在使用BeautifulSoup阅读网页的内容。我想要的是抓住以<a href>开头的http://。我知道在beautifulsoup你可以搜索属性。我想我只是遇到语法问题。我想它会有类似的东西。

page = urllib2.urlopen("http://www.linkpages.com")
soup = BeautifulSoup(page)
for link in soup.findAll('a'):
    if link['href'].startswith('http://'):
        print links 

但是回归:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python26\lib\BeautifulSoup.py", line 598, in __getitem__
    return self._getAttrMap()[key]
KeyError: 'href'

有什么想法吗?提前谢谢。

修改的 这不适用于任何网站。该脚本从用户获取URL。所以内部链接目标将是一个问题,这也是我只想要页面中<'a'>的原因。如果我将它转向www.reddit.com,它会解析开始的链接并且它会到达:

<a href="http://www.reddit.com/top/">top</a>
<a href="http://www.reddit.com/saved/">saved</a>
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python26\lib\BeautifulSoup.py", line 598, in __getitem__
    return self._getAttrMap()[key]
KeyError: 'href'

4 个答案:

答案 0 :(得分:6)

from BeautifulSoup import BeautifulSoup
import re
import urllib2

page = urllib2.urlopen("http://www.linkpages.com")
soup = BeautifulSoup(page)
for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
    print link

答案 1 :(得分:1)

您是否有一些没有<a>属性的href个标签?也许是内部链接目标?

答案 2 :(得分:0)

请告诉我们你在这里解析的内容 - 正如安德鲁指出的那样,似乎有一些锚标签没有相关的hrefs。

如果你真的想忽略它们,可以将它包装在try块中,然后用

进行捕获

except KeyError: pass

但这有其自身的问题。

答案 3 :(得分:0)

f=open('Links.txt','w')
import urllib2
from bs4 import BeautifulSoup
url='http://www.redit.com'
page=urllib2.urlopen(url)
soup=BeautifulSoup(page)
atags=soup.find_all('a')
for item in atags:
    for x in item.attrs: 
        if x=='href':
            f.write(item.attrs[x]+',\n')
        else:
            continue
f.close()

效率较低的解决方案。

相关问题