python - 将网页中的表值附加到 csv
问题描述
我想从网页中获取表格
import os
from webdriver_manager.chrome import ChromeDriverManager
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--start-maximized')
options.page_load_strategy = 'eager'
options.add_argument("--headless");
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 20)
driver.get("https://munafasutra.com/nse/dividends")
file_object = open('divident.csv', 'a')
输出表
如何获取第一个表及其值?
解决方案
您必须查看 HTML 路径并找到收集第一个表的 WebElement(单击鼠标右键时单击“检查”可以完成工作)。
您可以使用以下代码行保存该 web 元素:
first_table = driver.find_element_by_xpath("//div[@id = 'co']//table[1]") # The [1] is not really necessary as when using **find_element_by_xpath** will only look for the first element.
然后,如果您查看该表内的数据是如何组织的,您可以观察到每一行都是由tr WebElement 收集的。因此,如果您希望将其写入 csv 文件,我建议您使用以下代码逐行编写:
rows = first_table.find_elements_by_xpath("./tbody/tr")
for row in rows:
entries_of_the_row = row.find_elements_by_xpath("./td")
row_to_csv = []
for entry in entries_of_the_row:
row_to_csv.append(entry.text)
file_object.write(f"{row_to_csv[0]}, {row_to_csv[1]}, {row_to_csv[2]}, {row_to_csv[3]}, {row_to_csv[4]}\n")
file_object.close()