我是python
的新手。我想使用BeautifulSoup
在论坛中获取发布日期。我尝试了很多方法,但无法得到正确的结果。
这是我的问题:
<td class = by>
<cite>...</cite>
<em>
<span>2015-11-13</span>
</em>
</td>
<td class = ...>...</td>
<td class = by>...</td>
<cite>...</cite>
<em><a>...</a></em>
</td>
有两个同名“by
”的类,但我只想在第一个带有“span
”标签的日期。
这是我尝试过但不知道问题是什么:
cat=1
for span in soup.findAll('span', {'class':"by"}):
print (span.text)
一般的解决方案可能是迭代<td>
的class='by'
并找到<span>
。来自bs4进口BeautifulSoup
a="""<td class = by>
<cite>...</cite>
<em>
<span>2015-11-13</span>
</em>
</td>
<td class = ...>...</td>
<td class = by>...</td>
<cite>...</cite>
<em><a>...</a></em>
</td>"""
soup = BeautifulSoup(a, 'html.parser')
for item in soup.find_all("td",{"class": "by"}):
for i in item.find_all("span"):
print(i.text) # 2015-11-13
一种更直接的方法是
soup.select('td.by > em > span')[0].text # 2015-11-13
如果您只关注第一次出现,那么@Jon Clements建议您可以使用
soup.select_one('td.by > em > span').text