如何找到正确的xpath和循环覆盖表?

2024-10-01 04:49:28 发布

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

我想从https://powerhouse.net/forecast-prijzen-onbalans/上的“elektricitet NL”表中获取所有值。然而,在无休止地尝试使用selenium找到正确的xpath之后,我还是没能找到这个表。在

我尝试使用“inspect”并从表中复制xpath来标识表的长度,以便以后进行刮取。失败后,我试图使用“包含”,但这也没有成功。后来,我试了一些东西用美丽的汤,但没有任何运气。在

#%%
import pandas as pd

from selenium import webdriver
import pandas as pd
#%% powerhouse Elektriciteit NL base & peak

url = "https://powerhouse.net/forecast-prijzen-onbalans/"

#%% open webpagina
driver = webdriver.Chrome(executable_path = path + 'chromedriver.exe')
driver.get(url)

#%%
prices = []


#loop for values in table
for j in range(len(driver.find_elements_by_xpath('//tr[@id="endex_nl_forecast"]/div[3]/table/tbody/tr[1]/td[4]'))):
    base = driver.find_elements_by_xpath('//tr[@id="endex_nl_forecast"]/div[3]/table/tbody/tr[1]/td[4]')[j]


#%%
#trying with BeautifulSoup
from bs4 import BeautifulSoup
import requests 


response = requests.get(url)

soup = BeautifulSoup(response.content, "html.parser")

table  = soup.find('table', id = 'endex_nl_forecast')
rows = soup.find_all('tr')

我希望将表放在一个数据帧中,并理解xpath是如何工作的。我对整个概念还不熟悉。在


Tags: httpsimportidurldrivernltablefind
2条回答

您可以使用Selenium驱动程序定位表及其内容

url = 'https://powerhouse.net/forecast-prijzen-onbalans/'
driver.get(url)

time.sleep(3)

读取表格标题和打印

^{pr2}$

查找表中的行数

rowElements = driver.find_elements_by_xpath("//*[@id='endex_nl_forecast']//tbody/tr")
print('Total rows in the table:', len(rowElements))

按原样打印每行

for row in rowElements:
    print(row.text)

如果您对xpath以外的方法持开放态度,那么无需使用selenium或xpath就可以做到:

你可以用熊猫

import pandas as pd

table = pd.read_html('https://powerhouse.net/forecast-prijzen-onbalans/')[4]

如果需要图标的文本表示,可以从相应的td中提取描述箭头方向的{}类名

^{pr2}$

样本行:

enter image description here

相关问题 更多 >