我正在尝试从网站中提取日期。 html代码如下
<div class="tcell" style="width:175px;">
<!-- status icon and date -->
<a name="post6425787"><img alt="Old" class="inlineimg" src="https://www.f150forum.com/images/statusicon/post_old.gif"/></a>
12-10-2019, 06:13 PM
<!-- / status icon and date -->
</div>,
<div class="tcell">Smawgunner</div>,
<div class="tcell" style="width:175px;">
<!-- status icon and date -->
<a name="post6425799"><img alt="Old" class="inlineimg" src="https://www.f150forum.com/images/statusicon/post_old.gif"/></a>
12-10-2019, 06:18 PM
<!-- / status icon and date -->
</div>,
<div class="tcell">CKsBAT</div>
我想通过忽略名称字段来仅提取日期。我的代码如下
date = posts.find_all(lambda tag: tag.name == 'div' and
tag.get('class') == ['tcell'])
for i in date:
print(i.text)
上面的代码给出了日期和名称。如何从 HTML 代码中仅获取日期?预先感谢您
最佳答案
最直接的是,您可以使用 select
和 :nth-child(odd)
:
from bs4 import BeautifulSoup
html = """
<div>
<div class="tcell" style="width:175px;">
<a name="post6425787">
<img alt="Old"
class="inlineimg"
src="https://www.f150forum.com/images/statusicon/post_old.gif"
/>
</a>
12-10-2019, 06:13 PM
</div>,
<div class="tcell">Smawgunner</div>,
<div class="tcell" style="width:175px;">
<a name="post6425799">
<img alt="Old"
class="inlineimg"
src="https://www.f150forum.com/images/statusicon/post_old.gif"
/>
</a>
12-10-2019, 06:18 PM
</div>,
<div class="tcell">CKsBAT</div>
</div>
"""
soup = BeautifulSoup(html, "lxml")
for x in soup.select("div.tcell:nth-child(odd)"):
print(x.text.strip())
输出:
12-10-2019, 06:13 PM
12-10-2019, 06:18 PM
如果您需要基于内容性质的精度,您可以使用与您的日期格式完全匹配的正则表达式(除了空格之外什么都没有包围;根据需要放松正则表达式):
import re
soup = BeautifulSoup(html, "lxml")
pattern = r"^\s*(\d\d-){2}\d{4}, \d\d:\d\d [AP]M\s*$"
for x in soup.find_all(text=re.compile(pattern)):
print(x.strip())
如果您的日期格式不确定并且您想要获取任何可以解析为日期的内容:
from dateutil.parser import parse as parse_date
soup = BeautifulSoup(html, "lxml")
def try_parse_date(s):
try: return parse_date(s, fuzzy=True)
except ValueError: pass
for x in soup.find_all(text=try_parse_date):
print(x.strip())
关于python - 如何在Python中忽略同一div但不同类中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59651872/