首页 > 解决方案 > 如何使用 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 的安全搜索或按上传日期搜索怎么办?Selenium 有没有办法做到这一点?另外,每次运行代码时我只得到 35 个结果,我怎样才能增加这个数字?

标签: pythonseleniummicrosoft-edge

解决方案


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

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

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

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

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

完整的网址是这样的:

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()

对于搜索结果编号,我没有发现可以更改它的选项。


推荐阅读