0

我想在以下链接上废弃一些数据:

http://www.six-structured-products.com/en/search-find/new-search#search_type=profi&class_category=svsp

我的目标只是在data.frame. 我不能简单地使用urlliburllib2检索静态数据,因为我需要通过单击按钮来模仿人类:Ghost或者Selenium是要走的路。

但是,我真的不明白如何翻译成代码“点击第 2 页”、“点击第 3 页”......以及获取总页数。

我的代码:

from ghost import Ghost

url = "http://www.six-structured-products.com/en/search-find/new-search#search_type=profi&class_category=svsp"

gh = Ghost()
page, resources = gh.open(url)

我被困在那里,不知道放哪个标识符而不是 XXX:

page, resources = ghost.evaluate(
"document.getElementById(XXX).click();", expect_loading=True)

(我也会接受使用的解决方案Selenium

4

2 回答 2

1

做一个无限循环增加页面索引。当您没有找到具有当前索引的按钮时退出循环:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time

driver = webdriver.Firefox()
driver.get('http://www.six-structured-products.com/en/search-find/new-search#search_type=profi&class_category=svsp')

page = 2  # starting page
while True:
    try:
        button = driver.find_element_by_xpath('//ul[@id="pagination_pages"]/li[@class="pagination_page" and . = "%d"]' % page)
    except NoSuchElementException:
        break

    time.sleep(1)
    button.click()

    page += 1

print page  # total number of pages

driver.close()

请注意,time.sleep()更可靠的方法是使用Waits代替。

于 2014-12-14T19:41:29.643 回答
1

您也可以这样使用下一个按钮:

import logging
import sys

from ghost import Ghost, TimeoutError


logging.basicConfig(level=logging.INFO)

url = "http://www.six-structured-products.com/en/search-find/new-search#search_type=profi&class_category=svsp"

ghost = Ghost(wait_timeout=20, log_level=logging.CRITICAL)
data = dict()


def extract_value(line, ntd):
    return line.findFirst('td.DataItem:nth-child(%d)' % ntd).toPlainText()


def extract(ghost):
    lines = ghost.main_frame.findAllElements(
        '.derivativeSearchResult > tbody:nth-child(2) tr'
    )

    for line in lines:
        symbol = extract_value(line, 2)
        name = extract_value(line, 5)
        logging.info("Found %s: %s" % (symbol, name))
        # Persist data here

    ghost.sleep(1)

    try:
        ghost.click('.pagination_next a', expect_loading=True)
    except TimeoutError:
        sys.exit(0)

    extract(ghost)


ghost.open(url)
extract(ghost)
于 2015-01-09T20:17:24.043 回答