我在弄清楚如何指定页面上的最后 60 个元素时遇到了一些困难
posts = driver.find_elements_by_xpath("""(//div[@class='hotProductDetails'])""")
for post in posts:
print(post.text)
此代码打印网页上这些元素中的每一位文本。但我正在尝试抓取一个带有“加载更多”按钮的网站。
“加载更多”按钮加载 60 多个产品,我希望我的代码只获取这些产品。这样我就可以将所有内容放在一个循环中,单击按钮,获取它加载的产品,附加到 Pandas Dataframe 并重复一定数量的迭代。
我一直无法获得为我执行此操作的代码,一旦多次按下“加载更多”按钮,抓取元素就会杀死 chrome,进而杀死我的脚本。
"(//div[@class='hotProductDetails'])[position() > {} and position() <= {}])".format ((page -1 ) * 50, page * 50)
有人与我分享了这段代码,但它因以下错误而使我崩溃:
invalid selector: Unable to locate an element with the xpath expression (//div[@class='hotProductDetails'])[position() > {} and position() <= {}])".format ((page -1 ) * 50, page * 50 because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '(//div[@class='hotProductDetails'])[position() > {} and position() <= {}])".format ((page -1 ) * 50, page * 50' is not a valid XPath expression.
(Session info: chrome=60.0.3112.90)
(Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 10.0.14393 x86_64)
这是我第一次进行网络抓取项目并使用 Selenium(这是一个令人惊叹的软件包,给它留下了深刻的印象),我不知道如何修复它。我怀疑这与“页面”代码有关,因为所有内容都位于同一个网页上,当您加载更多产品时,该网页会变得更大。
如果有帮助的话,我可以分享我正在抓取的网站 - 就像我说的,这是我的第一个抓取项目,也是我刚刚加入的一家公司的项目。我不知道我分享这件事他们是否会感到不安。