【问题标题】:Pulling top results with Selenium in Python在 Python 中使用 Selenium 获得最佳结果
【发布时间】:2017-07-17 03:39:09
【问题描述】:

我正在尝试输入搜索词并从搜索中获取热门网址列表。我是 Selenium 的新手,不知道自己在做什么。到目前为止,我一直在关注这个教程:https://www.youtube.com/watch?v=EELySnTPeyw&t=21s

一切正常,直到返回热门网址。我使用的 xPath 是经过检查后直接来自谷歌上的元素。这是我当前的代码:

from selenium import webdriver

def get_results(search_term):
    url = "https://www.google.com"

    driver = webdriver.Chrome()
    driver.get(url)
    search_box = driver.find_element_by_id("lst-ib")
    search_box.send_keys(search_term)
    search_box.submit()

    links = driver.find_element_by_xpath("//*[@id="rso"]/div[3]/div/div[1]/div/h3/a")

    results = []
    for link in links:
        href = link.get_attribute("href")
        print(href)
        results.append(href)

    driver.close()
    return results


get_results("Who is the president of the united states?")

运行此程序时,我在 xPath ("//*[@id="rso"]/div[3]/div/div[1]/div/h3/a") 上不断收到无效语法错误。关于为什么这不起作用的任何想法?谢谢

【问题讨论】:

  • 如果你想得到list的元素,你应该使用find_elements_by_xpath()而不是find_element_by_xpath()

标签: python html google-chrome selenium xpath


【解决方案1】:

记住你应该在find_element_by_xpath中使用字符串。

所以你可以改变

"//*[@id="rso"]/div[3]/div/div[1]/div/h3/a"

"//*[@id='rso']/div[3]/div/div[1]/div/h3/a"

所以可以全部是String。

【讨论】:

  • 我试过了,它仍然显示这个错误:Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='rso']/div[3]/div/div[1]/div/h3/a"}
  • 这是另一个问题,这表明 XPath 选择了该元素。改用 CSS 选择器怎么样?
  • 您可以通过find_elements_by_css_selector使用CSS Selector
  • 它仍然显示相同的错误,只是使用 css 选择器路径。我想我可能只使用 python Requests 而不是 Selenium。反正我听说这样更好。感谢您的帮助
【解决方案2】:

你使用这个 xpath:

("//*[@id='rso']//h3/a")

您应该使用 find_elements_by_xpath 来获取列表对象的结果。 find_element_by_xpath 只返回第一个元素。

find_element(s)_by_xpath

【讨论】:

  • 每当我将 fin_element 更改为 find_elements 时,该功能都不起作用。 Chrome 将打开,然后立即关闭。我尝试了你提到的 xpath,由于某种原因它仍然返回一个没有这样元素的错误
【解决方案3】:

这应该可行:

links = driver.find_elements_by_xpath("""//*[@id="rso"]/div/div/div/div/div/h3/a""")

解释是 URL 的 xpath 没有遵循模式,所以当这种情况发生时,您只需删除导致错误的路径的 [n]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2021-09-30
    • 1970-01-01
    • 2011-03-05
    相关资源
    最近更新 更多