我试图从这个网站获取世界人口: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/