尊敬的stackoverflow社区,
我最近在尝试从中提取数据时遇到麻烦
https://www2.sgx.com/securities/corporate-information?country=SINGAPORE
我的目的是单击表中的每个链接,从3CNERGY LIMITED开始,该链接会打开另一个网页选项卡,进行提取,然后在提取后关闭该选项卡,然后返回主页,然后单击下一个链接。
我的问题是: 无法找到让我循环通过表的元素,并且 无法从主页切换到标签页,然后再返回。
我的进度: 我以为
<sgx-table-list data-rendered-rows="20" data-visible-rows="10" style="min-width: 560px; transform: translateY(0px);" data-rendered-index="0" data-visible-index="0" xpath="1">
将允许我循环通过表,但len仅返回1。
我已经能够使用以下方法单击第一个网页:
CE = driver.find_element_by_xpath("//a[contains(@href, 'infopub')]")
但是该脚本无法遍历表,只能执行第一次单击。另外,我无法更改它以通过xpath查找元素,因为它成为列表并且.click()不起作用。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
继续,尝试以下操作。我使用了XPath Helper Wizard,它是Chrome的插件。
链接中的主表:(更改sgx-table-row [ RowNumberHere ]以遍历第1列中的公司)
driver.find_element_by_xpath("//sgx-table-row[1]/sgx-table-cell-link[contains(@class, 'sgx-table-cell')]").click()
“公司”链接内部的链接:(将/ tr [ RowNumberHere ]更改为变量以进行循环)
driver.find_element_by_xpath("//table[3]/tbody/tr[1]/td[contains(@class, 'basicInfoContentContainerRight')]")
返回页面:
driver.back()
答案 1 :(得分:0)
这应该很简单。流程应如下所示:
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)