Python selenium从表和cli中提取数据

2024-05-23 15:59:15 发布

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

尊敬的stackoverflow社区:

我最近在试图从中提取数据时遇到了麻烦:

https://www2.sgx.com/securities/corporate-information?country=SINGAPORE

我的目的是单击表中的每个链接,从3Cenergy LIMITED开始,打开另一个网页选项卡,提取该选项卡,提取后关闭该选项卡,返回主页,然后单击下一个链接。在

我的问题是: 找不到允许我遍历表和 无法从主网页切换到选项卡,然后再切换回。在

我的进步: 我想

^{pr2}$

允许我循环检查表,但是len只返回1。。在

我可以使用以下方法单击第一个网页:

CE = driver.find_element_by_xpath("//a[contains(@href, 'infopub')]")

但是由于不能循环遍历表,脚本只执行第一次单击。另外,我不能将其更改为通过xpath查找元素,因为它变成了一个列表,.click()不能工作。在

任何帮助将不胜感激。谢谢!!在


Tags: 数据httpscom网页information链接corporatestackoverflow
2条回答

这应该很简单。流程应该是这样的:

  1. 导航到页面
  2. 关闭弹出对话框
  3. 等待数据加载
  4. 在公司链接中循环单击每个链接,从新选项卡获取数据,关闭新选项卡,切换回主窗口

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "https://www2.sgx.com/securities/corporate-information?country=SINGAPORE"
driver.get(url)

wait = WebDriverWait(driver, 10)

# close the preview warning dialog
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#beta-warning-dialog button"))).click()

# wait for the data to be loaded
company_name_locator = (By.CSS_SELECTOR, "div.table-container a")
wait.until(EC.visibility_of_element_located(companyNameLocator))

main_window_handle = driver.current_window_handle
# loop through visible company links
links = list(filter(lambda e: e.is_displayed(), driver.find_elements(companyNameLocator)))
for link in links
    link.click()

    # wait for new tab to open
    wait.until(lambda d: len(d.window_handles) == 2)
    driver.switch_to_window(driver.window_handles[1])

    # scrape something off the page
    print(wait.until(EC.visibility_of_element_located(By.ID, "ctl07_lblCompName")).text)

    # close the current tab
    driver.close()

    # wait for the tab to be closed and switch back to the main tab
    wait.until(lambda d: len(d.window_handles) == 1)
    driver.switch_to_window(main_window_handle)

试试下面的方法。我使用了XPath Helper Wizard,这是chrome的一个插件。在

链接中的主表:(将sgx表格行[RowNumberHere]更改为循环访问第1列中的公司)

driver.find_element_by_xpath("//sgx-table-row[1]/sgx-table-cell-link[contains(@class, 'sgx-table-cell')]").click()

在Company link链接内:(将/tr[RowNumberHere]更改为变量以进行循环)

^{pr2}$

返回页面:

driver.back()

相关问题 更多 >