【问题标题】:accessing values in subgroups in html code在 html 代码中访问子组中的值
【发布时间】:2013-08-27 08:11:19
【问题描述】:

我希望输出为“印地语”、“英语”。我能够获得“印地语”,但在输出“英语”时遇到了困难

输入:

<td class="_480u">
<div class="clearfix">
<div><a data-hovercard="/ajax/hovercard/page.php?id=112969428713061" href="https://www.facebook.com/pages/Hindi/112969428713061">Hindi</a> and 
      <a data-hovercard="/ajax/hovercard/page.php?id=106059522759137" href="https://www.facebook.com/pages/English/106059522759137">English</a></div></div></td>

我试过的代码:

>>> details.find('a',{'class':''}).string
u'Hindi'

s = details.findAll('a',{'class':''})
s1 = len(s)
list2 = []
if s1 >= 1:
   for j in range(0,s1):
      lang = s[j].find('a',{'class':''}).string.strip()
      list2.append(lang)
Traceback (most recent call last):
  File "<pyshell#220>", line 9, in <module>
    lang = s[j].find('a',{'class':''}).string.strip()
AttributeError: 'NoneType' object has no attribute 'string'


>>> s
[<a data-hovercard="/ajax/hovercard/page.php?id=112969428713061" href="https://www.facebook.com/pages/Hindi/112969428713061">Hindi</a>, <a data-hovercard="/ajax/hovercard/page.php?id=106059522759137" href="https://www.facebook.com/pages/English/106059522759137">English</a>]

【问题讨论】:

    标签: python python-2.7 html-parsing beautifulsoup


    【解决方案1】:

    如果那是确切的 HTML,那不会被改变,你可以使用这个:

    from bs4 import BeautifulSoup
    
    html = '<td class="_480u">\
    <div class="clearfix">\
    <div><a data-hovercard="/ajax/hovercard/page.php?id=112969428713061" href="https://www.facebook.com/pages/Hindi/112969428713061">Hindi</a> and \
          <a data-hovercard="/ajax/hovercard/page.php?id=106059522759137" href="https://www.facebook.com/pages/English/106059522759137">English</a></div></div></td>'
    
    soup = BeautifulSoup(html)
    print soup.find('a',{'class':''}).string
    print soup.find('a',{'class':''}).nextSibling.nextSibling.string
    

    输出:

    Hindi
    English
    

    或者你可以这样做(如果你只使用你在问题中发布的 HTML):

    from bs4 import BeautifulSoup
    
    html = '<td class="_480u">\
    <div class="clearfix">\
    <div><a data-hovercard="/ajax/hovercard/page.php?id=112969428713061" href="https://www.facebook.com/pages/Hindi/112969428713061">Hindi</a> and \
          <a data-hovercard="/ajax/hovercard/page.php?id=106059522759137" href="https://www.facebook.com/pages/English/106059522759137">English</a></div></div></td>'
    
    soup = BeautifulSoup(html)
    lang = soup.findAll('a', href = True)
    for i in lang:
        print i.string
    

    输出:

    Hindi
    English
    

    【讨论】:

    • 我使用第二种方法得到“RuntimeError: maximum recursion depth exceeded”
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多