我正在使用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