【问题标题】:beautifulsoup parse html tag exceptionbeautifulsoup 解析 html 标签异常
【发布时间】:2017-10-30 10:57:58
【问题描述】:

我正在从 html 文件中提取一些信息。但是有些文件没有标签<p class="p p1"> date </p>,它返回

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

并且某些文件中的日期不在标签内。我发现一个是:

<time content="2005-11-11T19:09:08Z" itemprop="datePublished">
 Nov. 11, 2005  2:09 PM ET
</time>

我该如何解决这两个问题?

我的代码:

month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December', 'Jan', 'Feb', 'Aug', 'Oct', 'Dec']


def first_date_p():

    for p in soup.find_all('p', {"class": "p p1"}):
        for month in month_list:
            if month in p.get_text():
                first_date_p = p.get_text()
                date_start = first_date_p.index(month)
                date_text = first_date_p[date_start:]
                return date_text
            else:
            #if the tag exist, but do not have date.
                month = 'No Date/Error'
                return month.strip()

【问题讨论】:

  • 在我看来,您应该首先寻找适用于所有 HTML 文件的日期特征。实际上,日期可能有不止一种格式,您需要分别处理每种格式。你有多少种不同的格式?

标签: python web-scraping beautifulsoup tags html-parsing


【解决方案1】:

如果要确保选定的“p”标签始终包含一些文本,可以将 text 参数设置为 True,即:

soup.find_all('p', {"class": "p p1"}, text=True)

否则,如果您想获取所有 'p',即使它们不包含任何文本,您也可以将 None 转换为字符串,例如:

str(p.get_text()).strip()  

至于你的第二个问题,你可以选择'time'标签的'content'属性,例如:

soup.find('time').get('content')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2013-03-20
    • 2012-05-22
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多