为什么我的网页抓取代码返回[]?

2024-10-01 05:02:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从这个网站上抓取一些数据,https://eleccionesnacionales.corteelectoral.gub.uy/ResumenResultados.htm,我检查了这个页面,发现了这个

photo

知道了这一点,我对它进行了编码,但它只返回“[]”我已经用了2个小时了,但我找不到解决方案

import requests from bs4 import BeautifulSoup url = requests.get("https://eleccionesnacionales.corteelectoral.gub.uy/ResumenResultados.htm") soup = BeautifulSoup(url.content, "lxml") votos = soup.find_all("span", class_="subtotal sin-margin sin-padding ") print(votos)

Tags: httpsimporturl网站sinrequestssouphtm
2条回答

使用这个JSON API。 我不知道为什么这个号码是“1591673487333”,但最恰当的说法是这是他的约会

https://eleccionesnacionales.corteelectoral.gub.uy/JSON/ResumenGeneral_D.json?1591673487333

此JSON文件的输出https://pastebin.com/yXvkArBv

使用此代码生成数字。像这样的“1591673487333”

import time
millis = int(round(time.time() * 1000))
print(millis)

例如:

import time
import urllib.request, json 

millis = int(round(time.time() * 1000))

with urllib.request.urlopen("https://eleccionesnacionales.corteelectoral.gub.uy/JSON/ResumenGeneral_D.json?" + str(millis)) as url:
    data = json.loads(url.read().decode())
    print(data)
    print(data[0]['EleccionNacional'][0]['LemaNombre']) # Partido Frente Amplio
    print(data[0]['EleccionNacional'][0]['Total']) # 949376

enter image description here

此代码将为您提供一个输出

import requests
from bs4 import BeautifulSoup

url = requests.get("https://eleccionesnacionales.corteelectoral.gub.uy/ResumenResultados.htm")
soup = BeautifulSoup(url.content, "lxml")
# print(soup)
votos = soup.find_all("span", {"class":"subtotal sin-margin sin-padding"})
for span in votos:
    print(span.text)
print(votos)

这是任何网站的一般程序。但是您提供的网站正在使用一些模板引擎,数据作为一些变量呈现,如下所示

{{Total | format . 0 }}

程序的输出将是

{{Total | format . 0 }}
{{Total | format . 0 }}
[<span class="subtotal sin-margin sin-padding">{{Total | format . 0 }}</span>, <span class="subtotal sin-margin sin-padding">{{Total | format . 0 }}</span>]

但是,如果您想获得它,请参阅此页:How to retrieve the values of dynamic html content using Python

它将使用selenium和chrome驱动程序获取实际渲染的站点,并使用它来刮取数据

相关问题 更多 >