首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用漂亮的汤从li标签中抓取日期?

如何使用漂亮的汤从li标签中抓取日期?
EN

Stack Overflow用户
提问于 2021-08-16 20:51:09
回答 2查看 40关注 0票数 0

我抓取了特定类的所有li标记,并得到了输出:

代码语言:javascript
运行
复制
<li>Aug 14-18, <a href="https://ai4good.org/fragile-earth-2021/">Fragile Earth 2021</a>, develop radically new technological foundations for advancing and meeting the Sustainable Development Goals. Online KDD-21 workshop.
</li>

<li>Aug 19-26, <a href="https://ijcai-21.org/">IJCAI-21: 30th Int. Joint Conference on Artificial Intelligence</a>. Montreal-themed Virtual Reality, Online.
</li>

我可以分别提取href和text,但是我也希望将日期存储在一列数据帧中,或者至少分别获取日期。你知道我该怎么做吗?

以下是该网站的链接:https://www.kdnuggets.com/meetings/index.html#Y21-10

EN

回答 2

Stack Overflow用户

发布于 2021-08-16 20:57:14

我认为这应该可以做到这一点:

代码语言:javascript
运行
复制
from bs4 import BeautifulSoup

soup = BeautifulSoup("""<li>Aug 14-18, <a href="https://ai4good.org/fragile-earth-2021/">Fragile Earth 2021</a>, develop radically new technological foundations for advancing and meeting the Sustainable Development Goals. Online KDD-21 workshop.
</li>

<li>Aug 19-26, <a href="https://ijcai-21.org/">IJCAI-21: 30th Int. Joint Conference on Artificial Intelligence</a>. Montreal-themed Virtual Reality, Online.
</li>""", "lxml")
dates = [x.text.split(',')[0] for x in soup.find_all('li')]
print(dates)

输出:

代码语言:javascript
运行
复制
['Aug 14-18', 'Aug 19-26']
票数 1
EN

Stack Overflow用户

发布于 2021-08-16 21:00:12

可以使用.contents方法访问特定元素:

代码语言:javascript
运行
复制
from bs4 import BeautifulSoup


html = """
<li>Aug 14-18, <a href="https://ai4good.org/fragile-earth-2021/">Fragile Earth 2021</a>, develop radically new technological foundations for advancing and meeting the Sustainable Development Goals. Online KDD-21 workshop. </li>
<li>Aug 19-26, <a href="https://ijcai-21.org/">IJCAI-21: 30th Int. Joint Conference on Artificial Intelligence</a>. Montreal-themed Virtual Reality, Online. </li>
"""

soup = BeautifulSoup(html, "html.parser")

dates = [tag.contents[0].strip(', ') for tag in soup.find_all("li")]
print(dates)

输出:

代码语言:javascript
运行
复制
['Aug 14-18', 'Aug 19-26']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68809053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档