如何使用python使用javascript从网页中获取表格内容?

时间:2019-04-09 15:06:31

标签: javascript python selenium-webdriver web-scraping

我喜欢从page中获取表格内容。以下是我的代码,我得到了NaN(无数据)。数字为何不显示?如何获取具有相应数据的表?谢谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以从api中获得不错的json格式:

import requests
import pandas as pd

url = 'https://api.blockchain.info/stats'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
params = {'cors': 'true'}

data = requests.get(url, headers=headers, params=params).json()

# if you want it as a table
df = pd.DataFrame(data.items())

选项2:

让页面完全呈现。有一种更好的方法将wait与Selenium一起使用,但是很快就在其中花了5秒钟等待显示:

from selenium import webdriver
import pandas as pd
import time

url = 'https://www.blockchain.com/stats'


browser = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
browser.get(url)
time.sleep(5)

dfs = pd.read_html(browser.page_source)
print(dfs[0])

browser.close()

输出:

                    0                   1                   2   3
0         Blocks Mined                 150                 150 NaN
1  Time Between Blocks        9.05 minutes        9.05 minutes NaN
2       Bitcoins Mined  1,875.00000000 BTC  1,875.00000000 BTC NaN