python - 如何获取li标签内的链接?

标签 python python-2.7 beautifulsoup

我有这个代码:

import urllib
from bs4 import BeautifulSoup
url = "http://download.cnet.com/windows/"
pageHtml = urllib.urlopen(url)
soup = BeautifulSoup(pageHtml)
for a in soup.select("div.catFlyout a[href]"):
    print "http://download.cnet.com"+a["href"]

但是这段代码没有给出正确的输出。 正确的输出应该是这样的:

http://download.cnet.com/windows/security-software/
http://download.cnet.com/windows/browsers/
http://download.cnet.com/windows/business-software/
..
..
http://download.cnet.com/windows/video-software/

最佳答案

列表中有一些相对和绝对链接,仅当链接以 http 开头时才添加基本 url:

for a in soup.select("div.catFlyout a[href]"):
    if not a["href"].startswith("http"):
        print "http://download.cnet.com"+a["href"]
    else:
        print a["href"]

或者,使用 urlparse 检查链接是否是绝对的(取自 here ):

import urllib
import urlparse
from bs4 import BeautifulSoup

def is_absolute(url):
    return bool(urlparse.urlparse(url).scheme)

url = "http://download.cnet.com/windows/"
pageHtml = urllib.urlopen(url)
soup = BeautifulSoup(pageHtml)
for a in soup.select("div.catFlyout a[href]"):
    if not is_absolute(a['href']):
        print "http://download.cnet.com"+a["href"]
    else:
        print a["href"]

关于python - 如何获取li标签内的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695574/

相关文章:

python - 使用 Pulp 检索多个最优解

python - 在 Django 中上传文件时出现 OSError

使用索引的 Numpy 循环

python - 如何在 Windows 7 中安装 python freetype

python - BeautifulSoup 查找中的正则表达式使用

python - Web 抓取导致 403 禁止错误

python - 如何解决TypeError : can only concatenate str (not “types.GenericAlias” ) to str

python 正则表达式 : match a string with only one instance of a character

python-2.7 - 计算键字典中元组列表的部分数量

python - 不确定为什么 beautifulsoup 代码不会抓取网站