【问题标题】:How to select some urls with BeautifulSoup?如何使用 BeautifulSoup 选择一些 url?
【发布时间】:2011-11-28 02:09:55
【问题描述】:

我想抓取除最后一行和“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/'”,但如果没有它的列表会很好。做这个的最好方式是什么?谢谢。

【问题讨论】:

    标签: python screen-scraping beautifulsoup web-scraping


    【解决方案1】:

    我认为这可能是您正在寻找的。 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
    

    【讨论】:

    • @Doran:完美!感谢您的帮助。
    【解决方案2】:

    我会在 class=listings 的表中获取每个 tr。对于您想要的信息,您的搜索显然过于广泛。因为 HTML 有一个结构,所以您可以轻松地只获取表格数据。从长远来看,这比获取所有href并过滤您不想要的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
    

    【讨论】:

    • @dm03514:谢谢。但是for tr in soup.findAll('tr'): data_list = tr.children() 给出了TypeError: 'NoneType' object is not callable 错误。这是因为源中有超过 1 个表吗?
    • @dm03514: 同样link = soup.findAll("tr", { "class" : "listings" }) 返回一个空列表[]。我做错了什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2020-08-11
    相关资源
    最近更新 更多