【问题标题】:Iterating in Python and BeautifulSoup在 Python 和 BeautifulSoup 中迭代
【发布时间】:2011-03-05 18:33:27
【问题描述】:
soup = BeautifulSoup(html).findAll('div', 'thread')
  for i in soup:
    print i

我将只使用这部分代码,因为那是我陷入困境的地方。

Soup 返回一个列表,我尝试使用 ' '.join() 来获得一个文字字符串,但它不起作用,因为它应该是一个字符串,而不是一个标签。我猜这是某种错误。

迭代,它在屏幕上打印所有不带逗号的列表。

但我想要的是在 div cass="thread" 中获取一个 href 内容

我尝试了很多类似的东西

soup = BeautifulSoup(html).findAll('div', 'thread')
  for i in soup:
    print BeautifulSoup(i)('a')['href']

最后一个代码告诉我“NoneType”对象不是 callabe。

我尝试了很多组合,但我确实陷入了困境,我根本无法让它工作。经过多次失败的尝试,我不知道该怎么办。很郁闷。

【问题讨论】:

  • 用方括号替换“a”周围的括号。现在可以用了吗?

标签: python beautifulsoup


【解决方案1】:

应该是这样的

divs = BeautifulSoup(html).findAll('div','thread')  
for div in divs:  
    print div.find('a').attr['href'] # may it be map(a.attrs)['href'], I don't remember now

【讨论】:

    【解决方案2】:

    查看此模块/类的文档 (http://www.crummy.com/software/BeautifulSoup/documentation.html) - findAll 的第二个参数是 json 对象,而不是字符串。你有没有试过这个:

    BeautifulSoup(html).findAll('div', { 'class': 'thread' })
    

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多