我正在使用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'
reddit.com has this:。所以,这不是一个语法错误,它是API。 – 2010-03-23 18:48:22