首页 > 解决方案 > 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)

页面源截图

标签: htmlpython-3.xbeautifulsoup

解决方案


我不确定它是否会对您有所帮助,因为我无法在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是否要从脚本中获取更多数据

硒文档


推荐阅读