【问题标题】:Basic Python/Beautiful Soup Parsing基础 Python/美汤解析
【发布时间】:2013-11-26 23:21:06
【问题描述】:

说我用过

date = r.find('abbr')

得到

<abbr class="dtstart" title="2012-11-16T00:00:00-05:00">November 16, 2012</abbr>

我只想打印November 16, 2012,但如果我尝试

print date.string

我明白了

AttributeError: 'NoneType' object has no attribute 'string'

我做错了什么?

回答:这是我用于学习目的的最终工作代码:

soup = BeautifulSoup(page)
calendar = soup.find('table',{"class" : "vcalendar ical"})

dates = calendar.findAll('abbr', {"class" : "dtstart"})
events = calendar.findAll('strong')

for i in range(1,len(dates)-1):
    print dates[i].string + ': ' + events[i].string

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    soup.find('abbr').string 应该可以正常工作。 date一定有问题。

    from BeautifulSoup import BeautifulSoup
    
    doc = '<abbr class="dtstart" title="2012-11-16T00:00:00-05:00">November 16, 2012</abbr>'
    
    soup = BeautifulSoup(doc)
    
    for abbr in soup.findAll('abbr'):
        print abbr.string
    

    结果:

    2012 年 11 月 16 日

    根据添加到问题的代码进行更新:

    你不能这样使用text参数。

    http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text

    text 是一个参数,可让您搜索 NavigableString 对象 而不是标签

    您正在寻找文本节点,或者您正在寻找标签。文本节点不能有标签名称。

    也许你想要''.join([el.string for el in r.findAll('strong')])

    【讨论】:

    • 搜索元素时不要使用text=True。找到您想要的元素,然后使用这些元素的.string 属性。
    【解决方案2】:

    错误消息是说dateNone。您没有显示足够的代码来说明为什么会这样。实际上,使用您以最直接的方式发布的代码应该可以工作:

    import BeautifulSoup
    
    content='<abbr class="dtstart" title="2012-11-16T00:00:00-05:00">November 16, 2012</abbr>'
    r=BeautifulSoup.BeautifulSoup(content)
    date=r.find('abbr')
    print(date.string)
    # November 16, 2012
    

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 2018-05-08
      相关资源
      最近更新 更多