【问题标题】:Python BeautifulSoup4 get_text() or regexPython BeautifulSoup4 get_text() 或正则表达式
【发布时间】:2015-05-27 01:06:51
【问题描述】:

我正在使用 Python 2.7.5 和 BeautifulSoup4。 我需要从 html 标签中剪切文本。 我在命令后输出<a class="username offline popupctrl" href="member.php?20938-NarutoO" title="NarutoO je offline"><strong><font color="#5566CC">NarutoO</font></strong></a>

  print post_owner[0]

我只需要昵称:NarutoO 并且不想使用get_text()

我的代码:

post_owner = soup.findAll(attrs={'class':'username offline popupctrl'})
for row1 in post_owner:
    text = ''.join(row1.findAll(text=True))
    data1 = text.strip()
    text_file.write("USER NAME\n")
    member_count = member_count + 1
    data1 = data1.encode('utf-8')
    text_file.write(str(data1) + '\n')

我在其他帖子中使用了一些解决方案。如果我理解正确,findAll 会给我一个所有匹配项的列表。我的代码将连续打印所有匹配项。我只需要访问 post_owner 列表中的元素并在没有 html 标记的情况下使用它们。像这样的一些例子:

  print post_owner[0]
  print post_owner[4]
  print post_owner[2]
  .
  .
  .

抱歉解释不好,我真的很累:o

【问题讨论】:

  • get_text 显然是最佳选择时,您为什么不想使用它?
  • 因为当我将 get_text 与 findAll 一起使用时,它会返回错误代码。
  • 报错信息具体是什么?
  • AttributeError: 'ResultSet' 对象没有属性 'find'

标签: python regex beautifulsoup


【解决方案1】:

使用soup.selectget()

[i.get('title') for i in soup.select('.username')]

【讨论】:

    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多