gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:23:42 30 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 尝试使用 BeautifulSoup 从网页中获取绝对链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2502120/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com