【问题标题】:How to pass Selenium html page to htmlXpathSelector如何将 Selenium html 页面传递给 htmlXpathSelector
【发布时间】:2012-07-26 01:02:13
【问题描述】:

我需要抓取一个使用 javascript 的页面。 这就是我使用 Selenium 的原因。 问题是 selenium 无法获取所需的数据。

我想使用 htmlXmlSelector 来尝试获取数据。

如何将生成的 html selenium 传递给 htmlXmlSelector ?

【问题讨论】:

    标签: python selenium scrapy


    【解决方案1】:

    这是我的解决方案:只需从 selenium page_source 创建 htmlXpathSelector:

    hxs = HtmlXPathSelector(text=sel.page_source)
    

    【讨论】:

      【解决方案2】:

      尝试手动创建Response

      from scrapy.http import TextResponse
      from scrapy.selector import HtmlXPathSelector
      
      body = '''<html></html>'''
      
      response = TextResponse(url = '', body = body, encoding = 'utf-8')
      
      hxs = HtmlXPathSelector(response)
      hxs.select("/html")
      

      【讨论】:

      • Selenium 是如何发挥作用的?我做了 selenium.get(url)。如何进行?
      • 我没用过 selenium,但我想你可以从中得到page html source。让页面正文创建一个response,然后您可以在其上使用HtmlXPathSelector
      【解决方案3】:

      使用 Selenium 手动响应:

      from scrapy.spider import BaseSpider
      from scrapy.http import TextResponse
      from scrapy.selector import HtmlXPathSelector
      import time
      from selenium import selenium
      
      class DemoSpider(BaseSpider):
          name="Demo"
          allowed_domains = ['http://www.example.com']
          start_urls = ["http://www.example.com/demo"]
      
          def __init__(self):
              BaseSpider.__init__(self)
              self.selenium = selenium("127.0.0.1", 4444, "*chrome", self.start_urls[0])
              self.selenium.start()
      
          def __del__(self):
             self.selenium.stop()
      
          def parse (self, response):
              sel = self.selenium
              sel.open(response.url)
              time.sleep(2.0) # wait for javascript execution
      
              #build the response object from Selenium
              body = sel.get_html_source()
              sel_response = TextResponse(url=response.url, body=body, encoding = 'utf-8')
              hxs = HtmlXPathSelector(sel_response)
              hxs.select("//table").extract()
      

      【讨论】:

      • 如何在body = sel.get_html_source()这行之前使用sel,我需要做一个XPATH查询然后根据返回的元素,我需要e.click()一个一个然后下载get_html_source(),知道怎么做吗? sel 似乎没有对内容进行 xpath 查询的方法?
      猜你喜欢
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多