我正在尝试输入搜索字词,并从搜索中获取返回顶部网址的列表。我是Selenium的新手,并不确切知道我在做什么。到目前为止,我一直在关注本教程:https://www.youtube.com/watch?v=EELySnTPeyw&t=21s
一切正常,直到返回顶部网址。我正在使用的xPath直接来自google上的元素。这是我目前的代码:
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")
上不断收到无效语法错误。关于为什么这不起作用的任何想法?感谢
答案 0 :(得分: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"
所以它可以是所有字符串。
答案 1 :(得分:0)
您使用此xpath:
(" // * [@ id中=' RSO'] // H3 / A&#34)
您应该使用find_elements_by_xpath将结果作为列表对象。 find_element_by_xpath只返回第一个元素。
find_element(s)_by_xpath
答案 2 :(得分:0)
这应该有效:
links = driver.find_elements_by_xpath("""//*[@id="rso"]/div/div/div/div/div/h3/a""")
解释是URL xpath不遵循模式,因此当发生这种情况时,您只需要删除导致错误的路径的[n]
。