按时间范围和日期优化 Selenium Google 搜索结果

Refine Selenium Google search results by time frame and date

在使用 Selenium 和 Chrome 以及 python 自动执行 Google 搜索并获取排序链接后,我正在尝试优化我的结果。我可以使用脚本成功获得初始搜索结果并自动单击 'Tools' 按钮。

底线是我无法弄清楚访问所需的 HTML 标签和 select/click 时间范围下拉,默认为 'Any Time' 然后 select/click 'Relevance' 下拉按日期排序。我试过 Select 但我为该方法使用了错误的标签。我已经使用 inspect element 和 Katalon Recorder 来解决这个问题,但我遇到了语法错误,例如 "element not found"。感谢任何帮助。

driver.get('https://www.google.com/search')
search_field = driver.find_element_by_name("q")

search_field.send_keys("cheese")
search_field.submit()
#  Clicks the Tools button, activates sort dropdowns
driver.find_element_by_id("hdtb-tls").click()

# Need to sort results by last 24, week, month, etc.
driver.find_element_by_class_name('hdtb-mn-hd')
driver.find_element_by_link_text('Past month').click()

# Need to sort results date
driver.find_element_by_xpath('.//*[normalize-space(text()) and normalize- 
space(.)="To"])[1]/following::div[5]')
driver.find_element_by_link_text('Sorted by date').click()

你错过了 driver.find_element_by_class_name('hdtb-mn-hd')

.click()
driver = webdriver.Chrome()

driver.get('https://www.google.com/search')
search_field = driver.find_element_by_name("q")

search_field.send_keys("cheese")
search_field.submit()
#  Clicks the Tools button, activates sort dropdowns
driver.find_element_by_id("hdtb-tls").click()

# Need to sort results by last 24, week, month, etc.
driver.find_element_by_class_name('hdtb-mn-hd').click()
driver.find_element_by_link_text('Past month').click()

这是一个完整的脚本,它一直在运行:

from selenium import webdriver 
import time

driver = webdriver.Chrome()

driver.get('https://www.google.com/search')
search_field = driver.find_element_by_name("q")

search_field.send_keys("cheese")
search_field.submit()
#  Clicks the Tools button, activates sort dropdowns
time.sleep(1)
driver.find_element_by_id("hdtb-tls").click()

# Need to sort results by last 24, week, month, etc.
time.sleep(1)
driver.find_element_by_class_name('hdtb-mn-hd').click()
time.sleep(1)
driver.find_element_by_link_text('Past month').click()

# Need to sort results date
time.sleep(1)
driver.find_elements_by_xpath('//*[@id="hdtbMenus"]/div/div[3]/div')[0].click()
time.sleep(1)
driver.find_elements_by_xpath('//*[@id="sbd_1"]')[0].click()