如何使用 Selenium 更改搜索参数?

How to change search parameters using Selenium?

我制作了一个程序,该程序使用 Selenium 根据用户输入的搜索查询从 Bing 中获取随机图像。这是它的样子:

import random
from msedge.selenium_tools import EdgeOptions
from msedge.selenium_tools import Edge

query = "cats" #This can be anything
query.replace(' ', '+')

edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument('headless')
edge_options.add_argument('disable-gpu')

driver = Edge(executable_path='PATH/TO/DRIVER', options=edge_options)

#The URL that Edge generates when searching on Bing Images
ImageURL=f'https://www.bing.com/images/search?q={query}&form=HDRSC2&first=1&tsc=ImageBasicHover'

driver.get(ImageURL)

#An array with all the images that Selenium finds
all_images = driver.find_elements_by_class_name('mimg')
thumbnail = random.choice(all_images)

#Getting to the HTML that holds the image link
parent = thumbnail.find_element_by_xpath("..")
Grandparent = parent.find_element_by_xpath("..")
neededPage = Grandparent.get_attribute('href')

driver.get(neededPage)
image = driver.find_element_by_tag_name('img')
source = image.get_attribute('src')
print(source)

driver.quit()

一切正常,但我遇到了问题。我只能查找静态图像(Png、Jpg 等)。如果我想查找 GIF、关闭 Edge 的安全搜索或按上传日期搜索怎么办?有没有办法从硒中做到这一点?另外,我每次 运行 代码时只得到 35 个结果,我怎样才能增加这个数字?

添加搜索过滤器的方法有两种。

  1. 在url中添加搜索参数。

如果要添加搜索过滤器,可以在url中添加这个参数:qft=+filterui:xxx.

比如要搜索过去24小时内的gif动画,可以添加如下参数:

qft=+filterui:photo-animatedgif+filterui:age-lt1440

完整的url是这样的:

https://www.bing.com/images/search?q={query}&form=HDRSC2&first=1&tsc=ImageBasicHover&qft=+filterui:photo-animatedgif+filterui:age-lt1440
  1. 在代码中找到搜索过滤器。

正如 Piotr M 所说,您可以使用 css 选择器定位过滤器。

例如,如果你想搜索过去24小时内的动画gif,你可以在你的代码中添加以下部分:

filter = driver.find_element_by_id('fltIdtTit')
filter.click()
time.sleep(3)
m = driver.find_element_by_css_selector("span[title='Type filter']")
m.click()
p = driver.find_element_by_css_selector("a[title='Animated GIF']")
p.click()
n=driver.find_element_by_css_selector("span[title='Date filter']")
n.click()
q=driver.find_element_by_css_selector("a[title='Past 24 hours']")
q.click()

对于搜索结果编号,我没有找到更改它的选项。