html - Beautifulsoup python获取页面的日期和作者
问题描述
我正在尝试从页面的 html 代码中接收日期和名称,但我的代码不起作用。我正在尝试从这部分代码中提取。使用此 URL,我应该收到:我的心情和 10 июл 2016,但我收到错误消息。
我使用type="text/javascript"
作为搜索短语是因为这部分页面源代码以:(<script type="text/javascript">
这部分比我插入的要大得多,但我只需要这两个元素,作者和日期)
我从中提取的代码的 HTML 部分:
ajax.preload('al_photos.php', {"act":"show","list":"album-68872445_00\/rev","photo":"-68872445_422126739","module":"photos"}, ["album-68872445_00\/rev",7557,3696.000000,[{"id":"-68872445_422205711","base":"https:\/\/pp.userapi.com\/","commcount":0,"commshown":0,"comments":"<div id=\"pv_comments\" class=\"pv_comments wall_module\">\n <div id=\"pv_comments_header\" onclick=\"Photoview.comments();\" class=\"pv_comments_header unshown\"><\/div>\n <div id=\"pv_comments_list\" class=\"pv_comments_list unshown\"><\/div>\n <div class=\"pv_no_commments_placeholder_wrap\">\n <div class=\"pv_no_commments_placeholder no_rows unshown\">Будьте первым, кто оставит комментарий к этой фотографии.<\/div>\n <div class=\"pv_closed_commments_placeholder no_rows \">Возможность комментирования этой фотографии ограничена.<\/div>\n <\/div>\n<\/div>","reply_form":"","reply_options":[],"date":"<span class=\"rel_date\">10 июл 2016<\/span>","tags":[0],"tagged":[],"album":"<a href=\"\/album-68872445_00\" onclick=\"return nav.go(this, event)\">Фотографии на стене сообщества<\/a>","author":"<a href=\"\/lovely_detka_tytyty\" class=\"group_link\">my mood<\/a>"
我的代码:
from bs4 import BeautifulSoup
import requests
import lxml
import json
url = 'https://vk.com/photo-68872445_422126739?rev=1'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'lxml')
data = soup.select('type="text/javascript"')[0]
name = json.loads(data.text)["author"]
date = json.loads(data.text)["date"]
print (name)
print (date)
解决方案
我不确定它是否会对您有所帮助,因为我无法在script
标签内看到您的数据。但是,如果您的最终目的是获取日期和作者,请参见下面的代码:
from bs4 import BeautifulSoup
import requests
import lxml
import json
url = 'https://vk.com/photo-68872445_422126739?rev=1'
req = requests.get(url)
soup = BeautifulSoup(req.text, 'lxml')
dls = soup.find_all("dl",{'class':'si_row'})
for dl in dls:
atag = dl.find('a')
if atag:
author_link = atag.get('href')
author_name = atag.get_text()
print(author_link)
print(author_name)
span_date = soup.find('span',{'class':'item_date'})
if span_date:
date = span_date.get_text()
print(date)
编辑:
作为记录,您的错误可能是因为您正在使用requests
获取页面并且您正在搜索的数据在 ajax 响应中。您可以查看selenium
是否要从脚本中获取更多数据
推荐阅读
- html - 如何修改 AJAX 请求,以便在页面加载时隐藏空的依赖下拉菜单?
- r - R replace() 与逻辑测试冲突
- python - Matplotlib 底图动画需要更长的时间来处理更多帧
- r - 在图表上绘制多条线: geom_path:每组仅包含一个观察值。需要调整群体审美吗?
- amp-html - AMP-EMAIL:迭代来自 amp-state 的项目列表
- xcode11 - 创建 macOS 应用程序后关闭 Xcode 的解决方法?
- android-studio - 适用于所有 Google Play 用户的“此应用与您的所有设备都不兼容”
- html - 周一到周日自动突出显示工作日单元格。今天是星期二我想突出显示星期二,见附图
- git - 您的本地(不存在)更改将被结帐覆盖
- ansible - Vagrant 端口转发本地主机 8080 和 8000 到主机 8080 和 8000