【问题标题】:Extracting data tables from HTML source after scraping using Selenium & Python使用 Selenium 和 Python 抓取后从 HTML 源中提取数据表
【发布时间】:2023-04-05 12:06:01
【问题描述】:

我正在尝试从这个link 中抓取数据。我已经研究了被问到的问题,并且我已经成功地进行了一些抓取。但是我在生成的结果中几乎没有问题。以下是我用来抓取的一段代码。

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from datetime import datetime
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys

options = Options() 
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://www.scstrade.com/MarketStatistics/MS_HistoricalIndices.aspx') 

inputElement_index = driver.find_element_by_id("txtSearch")
inputElement_index.send_keys('KSE ALL')


inputElement_date = driver.find_element_by_id("date1")
inputElement_date.send_keys('03/12/2019')

inputElement_date_end = driver.find_element_by_id("date2")
inputElement_date_end.send_keys('03/12/2020')

inputElement_viewprice = driver.find_element_by_id("btn1")
inputElement_viewprice.send_keys(Keys.ENTER)

tabel = driver.find_elements_by_css_selector('table > tbody')[0]

目的是从link 中提取日期在 2020 年 3 月 12 日至 2020 年 3 月 3 日之间的数据,索引为KSE ALL。现在上面的代码可以工作,但是当代码第一次运行时,代码表对象的最后一行是空白的,如果我重新运行最后一行,它会以字符串格式给出第一页上的表格。 我想知道为什么我第一次运行代码时没有得到表格?如何为字符串中的表对象获取 pandas DataFrame?

我尝试使用以下代码将第一页数据放入 pandas DataFrame。但是表格对象原来是'NoneType'

htmlSource = driver.page_source
soup = BeautifulSoup(htmlSource, 'html.parser')
table = soup.find('table', class_='tbody')

其次,我想提取整个数据,而不仅仅是第一页上的数据和页数是动态的,它们会随着日期范围的变化而变化。现在转到下一页,我尝试了以下代码:

driver.find_element_by_id("next_pager").click()

我收到以下错误。

selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <td id="next_pager" class="ui-pg-button" title="Next Page">...</td> is not clickable at point (790, 95). Other element would receive the click: <div class="loading row" id="load_list" style="display: block;">...</div>

我试图查找如何解决这个问题,写了下面的代码来增加一些等待时间。但是得到了和上面一样的错误。

wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[title="Next Page"]'))).click()

如何移动到后续页面并从所有页面中提取数据(根据设置的日期范围,页面数将是动态的)并将其附加到从前一页中提取的数据中?

【问题讨论】:

    标签:
    python-3.x
    selenium
    web-scraping