如何使用BeautifulSoup选择一些链接?

2 投票
2 回答
1470 浏览
提问于 2025-04-17 03:23

我想抓取以下信息,但不包括最后一行和“class="Region"”这一行:

...
<td>7</td>
<td bgcolor="" align="left" style=" width:496px"><a class="xnternal" href="http://www.whitecase.com">White and Case</a></td> 
<td bgcolor="" align="left">New York</td> 
<td bgcolor="" align="left" class="Region">N/A</td> 
<td bgcolor="" align="left">1,863</td> 
<td bgcolor="" align="left">565</td> 
<td bgcolor="" align="left">1,133</td> 
<td bgcolor="" align="left">$160,000</td>
<td bgcolor="" align="center"><a class="xnternal" href="/nlj250/firmDetail/7"> View Profile </a></td></tr><tr class="small" bgcolor="#FFFFFF">
...

我用这个处理程序测试过:

class TestUrlOpen(webapp.RequestHandler):
    def get(self):
        soup = BeautifulSoup(urllib.urlopen("http://www.ilrg.com/nlj250/"))
        link_list = []
        for a in soup.findAll('a',href=True):
            link_list.append(a["href"])
        self.response.out.write("""<p>link_list: %s</p>""" % link_list)

这个方法有效,但它也抓取了“查看个人资料”的链接,我并不想要这个:

link_list: [u'http://www.ilrg.com/', u'http://www.ilrg.com/', u'http://www.ilrg.com/nations/', u'http://www.ilrg.com/gov.html', ......]

我可以在抓取完网站后轻松去掉“u'http://www.ilrg.com/'”,但如果能直接得到没有这个链接的列表就更好了。有什么好的方法吗?谢谢。

2 个回答

1

我会从类名为listings的表格中获取每一行(tr)。你的搜索范围显然太广,无法找到你想要的信息。因为HTML有一定的结构,你可以很容易地只获取表格中的数据。这样做比先获取所有的链接(href)然后再筛选出不需要的要简单得多。BeautifulSoup有很多文档可以帮助你了解如何做到这一点。http://www.crummy.com/software/BeautifulSoup/documentation.html

这不是确切的代码:

for tr in soup.findAll('tr'):
  data_list = tr.children()
  data_list[0].content  # 7
  data_list[1].content  # New York
  data_list[2].content # Region <-- ignore this
  # etc
3

我觉得这可能正是你想要的。attrs这个参数可以帮助你找到你想要的部分。

from BeautifulSoup import BeautifulSoup
import urllib

soup = BeautifulSoup(urllib.urlopen("http://www.ilrg.com/nlj250/"))

rows = soup.findAll(name='tr',attrs={'class':'small'})
for row in rows:
    number = row.find('td').text
    tds = row.findAll(name='td',attrs={'align':'left'})
    link = tds[0].find('a')['href']
    firm = tds[0].text
    office = tds[1].text
    attorneys = tds[3].text
    partners = tds[4].text
    associates = tds[5].text
    salary = tds[6].text
    print number, firm, office, attorneys, partners, associates, salary

撰写回答