javascript - 点击java元素scrapy+selenium

标签 javascript selenium xpath scrapy

我正在尝试抓取此页面:http://www.newyorkerfiction.com/Pieces.aspx与 scrapy 和 Selenium 。我需要点击不同的页面,但我找不到方法。我的脚本是:

def __init__(self):
    self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
    self.driver.set_window_size(1920, 1080); #Size

def parse(self, response):
    self.driver.get(response.url)
    element = self.driver.find_element(By.XPATH, '//div[@class="rgWrap rgNumPart"]//a[contains(@href, "javascript:__doPostBack")]')
    self.driver.execute_script("arguments[0].click();", element)
    self.driver.save_screenshot('screenshot.png')
    for sel in response.xpath('//body'):
        item = NyfictionItem()
        item["title"] = sel.xpath('//td[@class="title"]').extract()
        yield item
    self.driver.close()

我不明白出了什么问题,因为我知道execute_script使selenium与javascript中的元素交互。我测试了xpath,看起来是正确的。

有什么想法吗?

谢谢

最佳答案

一个问题是您的定位器指向分页栏中的所有链接,并且由于您获得的是第一个链接,因此您实际上是在尝试单击“1”链接,但是,您本来想单击“下一页”链接,可以使用 input.rgPageNext CSS 选择器找到。

但是,您需要wait for it to be visible and clickable使过程更加可靠:

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


driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
driver.set_window_size(1920, 1080)

driver.get("http://www.newyorkerfiction.com/Pieces.aspx")

wait = WebDriverWait(driver, 10)
next_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.rgPageNext")))
next_link.click()

driver.save_screenshot('screenshot.png')

driver.close()

请注意,单击“下一页”链接后,您可能需要再次等待才能加载新页面结果。

而且,您还需要一些额外的逻辑才能停在最后一页。

关于javascript - 点击java元素scrapy+selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43140489/

相关文章:

javascript - ChatClient 中服务器关闭/重置后未触发错误事件

javascript - onblur 事件包含 if 语句和函数调用

javascript - 使用 selenium python 访问下拉元素

java - 从 jar 文件启动时 Selenium 服务器没有响应

html - xPath/HTML : Select node based on related node

javascript - Kendo TreeView HierarchicalDataSource 中的歧义列

javascript - 使函数根据 AJAX 响应返回 false

java - 使用正则表达式从字符串中提取数字

python - 使用 XPath 解析定义列表的最佳方法是什么?

xml - XPath:如何选择具有一个或另一个属性的所有元素