python - 有没有办法从网站的检查菜单中获取有关元素的信息?

标签 python html web-scraping

我试图从这个网站获取世界人口:https://www.worldometers.info/world-population/ 但我只能得到html代码,不能得到实际数字的数据。

我已经尝试找到我尝试从中获取数据的对象的子对象。我也尝试列出整个对象,但似乎没有任何效果。

'''只是导入内容'''

import urllib.request

import requests

from bs4 import BeautifulSoup

'''从网站获取 html 到文本'''

r = requests.get('https://www.worldometers.info/world-population/')

soup = BeautifulSoup(r.text,'html.parser')

'''此处仅查找下面列出的一个对象'''

current_population = soup.find('div',{'class':'maincounter-number'}).find_all('span', recursive=False)

print(current_population)

这是存储信息的对象:

(span class="rts-counter" rel="current_population">retrieving data... </span>

在“检查模式”下您可以看到:

(span class="rts-counter" rel="current_population">(span class="rts-nr-sign"></span>(span class="rts-nr-int rts-nr-10e9">7</span>(span class="rts-nr-thsep">,</span>(span class="rts-nr-int rts-nr-10e6">703</span>(span class="rts-nr-thsep">,</span>(span class="rts-nr-int rts-nr-10e3">227</span><span class="rts-nr-thsep">,</span>(span class="rts-nr-int rts-nr-10e0">630</span></span>

我总是只得到第一个,但想从“检查模式”得到第二个。

Here是检查模式的图片。

最佳答案

您将需要一种让 javascript 运行的方法,例如 selenium,因为该数字是通过此脚本中生成的计数器设置的:https://www.realtimestatistics.net/rts/RTSp.js

from selenium import webdriver

d = webdriver.Chrome()
d.get('https://www.worldometers.info/world-population/')
print(d.find_element_by_css_selector('[rel="current_population"]').text)

您可以尝试编写您自己的 JavaScript 脚本版本,但我不推荐这样做。

我不需要 explicit wait Selenium 脚本的条件,但可以添加。

关于python - 有没有办法从网站的检查菜单中获取有关元素的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56090905/

相关文章:

python - 从数据流运行 tensorflow 模型训练

python - virtualenvwrapper默认将站点包存储在什么目录中?

python - 绝对时间到相对时间

html - 让按钮启动选项选择下拉菜单

javascript - 为什么在设置单个阿拉伯字符的样式时阿拉伯字符表现为单独的字符?

android - 无法使用 Phonegap 2.7 在 HTML5 Canvas 上绘图

python - BeautifulSoup:无法获取文本

python - 使用Python计算Excel中的值

web-scraping - 如何使用 iMacros 从元素中提取属性值?

php - 通过许多 url 在源代码中查找字符串的代码