如何在python beautifulsoup中获取下一页链接?

时间:2013-08-22 09:47:53

标签: python python-2.7 beautifulsoup

我有这个链接:

http://www.brothersoft.com/windows/categories.html

我正在尝试获取div中项目的链接。 例如:

http://www.brothersoft.com/windows/mp3_audio/midi_tools/

我试过这段代码:

import urllib
from bs4 import BeautifulSoup

url = 'http://www.brothersoft.com/windows/categories.html'

pageHtml = urllib.urlopen(url).read()

soup = BeautifulSoup(pageHtml)

sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brLeft'})]

for i in sAll:
    print "http://www.brothersoft.com"+i['href']

但我只得到输出:

http://www.brothersoft.com/windows/mp3_audio/

如何获得我需要的输出?

1 个答案:

答案 0 :(得分:2)

网址http://www.brothersoft.com/windows/mp3_audio/midi_tools/不在标记<div class='brLeft'>中,因此如果输出为http://www.brothersoft.com/windows/mp3_audio/,那就是正确的。

如果您想获得所需的网址,请更改

sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brLeft'})]

sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brRight'})]

<强>更新

获取'midi_tools'

内信息的示例
import urllib 
from bs4 import BeautifulSoup

url = 'http://www.brothersoft.com/windows/categories.html'
pageHtml = urllib.urlopen(url).read()
soup = BeautifulSoup(pageHtml)
sAll = [div.find('a') for div in soup.findAll('div', attrs={'class':'brRight'})]
for i in sAll:
    suburl = "http://www.brothersoft.com"+i['href']    #which is a url like 'midi_tools'

    content = urllib.urlopen(suburl).read()
    anosoup = BeautifulSoup(content)
    ablock = anosoup.find('table',{'id':'courseTab'})
    for atr in ablock.findAll('tr',{'class':'border_bot '}):
        print atr.find('dt').a.string      #name
        print "http://www.brothersoft.com" + atr.find('a',{'class':'tabDownload'})['href']   #link