【问题标题】:scrapy xpath: can't get google next pagescrapy xpath:无法获取谷歌下一页
【发布时间】:2015-03-22 02:52:48
【问题描述】:

我想在https://www.google.com.tw/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=test 中获取下一页

但我的代码不起作用。
请指导我。非常感谢。

  scrapy shell "https://www.google.com.tw/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=test"
 response.xpath("//a[@id='pnnext']/@href")

【问题讨论】:

  • 您没有收到您正在寻找的页面。使用命令 view(response) 打开浏览器

标签: python xpath scrapy


【解决方案1】:

您可以尝试使用下面的 x 路径并让我知道结果是什么。看起来使用的 xpath 没有指向 DOM 中 web 元素的确切位置。

//a[@id='pnnext']//span[2]

【讨论】:

  • 你确定这个解决方案吗?结果 []
  • @aberna :我同意你使用命令视图(响应),但我也在 DOM 中检查了 Web-Element ,我发现 Span[2] 可能更精确地指向。
【解决方案2】:

这是工作代码

scrapy shell "https://www.google.com.tw/search?q=test"
response.xpath("//a[@id='pnnext']/@href")

问题在于您向 Google 发出请求的方式。

在任何情况下都应注意处理 Google 搜索的政策。

可在http://www.google.com/cse/docs/tos.html 找到 Google 的自定义搜索服务条款 (TOS)。

更新: 我写了一个蜘蛛来更深入地测试这个问题。

根本不是pythonic(欢迎改进),但我对处理谷歌结果的机制很感兴趣。

正如之前的 cmets 所建议的,需要对接口的国际化进行测试。

class googleSpider(CrawlSpider):
    name = "googlish"
    allowed_domains = ["google.com"]
    start_urls = ["http://www.google.com"]

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)      
        login_form = self.driver.find_element_by_name('q')        
        login_form.send_keys("scrapy\n")
        time.sleep(4)
        found = False
        while not found:
            try :
                for element in self.driver.find_elements_by_xpath("//div[@class='rc']"):
                    print element.text + "\n"
                for i in self.driver.find_elements_by_id('pnnext'):
                    i.click()
                time.sleep(5)        
            except NoSuchElementException:
                found = True
                pass

        self.driver.close()

【讨论】:

  • @alecxe 有趣,值得深入分析。你知道原因吗?我从谷歌检查工具中取出 xpath 并将其应用于 shell 命令并且它工作。如果通过 shell 命令可视化页面会发生什么?它是正确的页面吗?
  • 谢谢,如果我这样做view(response),我实际上会看到搜索结果,并且底部有一个下一步按钮,尽管它没有pnnext id:<a href="/search?q=test&ie=UTF-8&prmd=ivnsa&ei=XJTCVOXlL4vvgwSjjISIBA&start=10&sa=N" style="text-align:left"><span class="csb" style="background-position:-96px 0;width:71px"></span><span style="display:block;margin-left:53px">�U�@��</span></a>。跨度>
  • @alecxe 对谷歌搜索不是那么专业,但这听起来是一种奇怪的行为。这样就需要一种不同的方法,比如搜索“下一个”标签
  • @alexce 尝试了一种不同的方法,使用 webdriver 来提取下一页结果。
猜你喜欢
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多