gpt4 book ai didi

python - beautifulsoup解析html标签异常

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:21 25 4
gpt4 key购买 nike

我正在从 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()

最佳答案

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

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

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

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

关于第二个问题,您可以选择“时间”标签的“内容”属性,例如:

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

关于python - beautifulsoup解析html标签异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44254249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com