python - 无法使用 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'
我得到 []
是否可以提取不在任何子标签中的数据?
解决方案
如果你抓住这些元素,你会注意到 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
推荐阅读
- python-3.x - PySide2 and pyinstaller gui application won't run on certain windows computers
- r - Get object and indices from subsetting call
- java - 访问外部类中的静态变量时静态内部线程的问题
- android - Calculate sum of recyclerview item double values
- asp.net - 在 MVC 编辑视图中将模型值设置为 CKeditor
- python - Cython 中的枚举成员名称重复 - 重新声明错误?
- azure - 如何在 ServiceBus 消息头中发送/接收数据
- php - 通过 phpmailer 发送巨大的 html 邮件
- node.js - 动态更改用户为 SPA (node.js) 实时提供的 html
- android - java.lang.IllegalStateException: context.getSharedPrefere...EF, Context.MODE_PRIVATE) 不能为空