首页 > 解决方案 > 无法使用 Python 和 Beautiful Soup 从网站中提取日期值

问题描述

我想从一个网站中提取日期。我想要发布新闻文章的日期/时间。这是我的代码:

从 bs4 导入 BeautifulSoup 导入请求

url = "http://buchholterberg.ch/de/Gemeinde/Information/News/Newsmeldung?filterCategory=22&newsid=911"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')


date_tag = 'div#middle p' # this gives me all the paragraphs
date = soup.select(date_tag)
print(date)

你也可以试试这个网站:

url = 'http://www.embrach.ch/de/aktuell/aktuellesinformationen/?action=showinfo&info_id=1098080'

请查看url,这是我要抓取的网站,我要获取的日期/时间是:13:05:28 26.11.2020

这是我的 css 选择器,它只给我段落,但日期/时间不在段落中,它在字体标签中。

date_tag = 'div#middle p'

但是当我将我的 CSS 选择器设置为:

date_tag = 'div#middle font'

我得到 []

是否可以提取不在任何子标签中的数据?

标签: pythonweb-scrapingbeautifulsoup

解决方案


如果你抓住这些元素,你会注意到 date 是<h1>标签的下一个兄弟节点。所以得到<div id="middle">标签。然后在该标签中,获取<h1>标签。然后从该<h1>标签中,获取.nextSibling.previousSibling如果它放置在某个标签元素之前,还有)这是文本。那么这只是一些字符串操作的问题。

代码:

import requests
from bs4 import BeautifulSoup

url = "http://buchholterberg.ch/de/Gemeinde/Information/News/Newsmeldung?filterCategory=22&newsid=911"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

date = soup.find_all('div',{'id':'middle'})
print(date)

for each in date:
    print(each.find('h1').nextSibling.split(':',1)[-1].strip())

输出:

13:05:28 26.11.2020

推荐阅读