python - 如何使用 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 个结果,我怎样才能增加这个数字?
解决方案
有两种方法可以添加搜索过滤器。
- 在 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
- 在代码中找到搜索过滤器。
就像 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()
对于搜索结果编号,我没有发现可以更改它的选项。
推荐阅读
- flutter - 如何修复 - 在调试模式下登录的 APK 问题 - Flutter 应用
- python - 如何将值从python中的配置文件传递给变量
- sql-server - 如何在 SSIS 作业步骤属性中使用环境文件
- mysql - 从单独的表中添加计数总计
- javascript - 使用 Redux 处理 UI 状态可以吗?
- php - PGBrowser 如何在另一个页面上重定向
- android - Android:android.content.res.Resources$NotFoundException:资源 ID #0x0 in
- mysql - 错误代码:1136。列计数与第 1 行的值计数不匹配
- python-3.x - Python 3:如何在 Python 中对 OLS 系数进行单边测试?
- ios - 带有自定义 NSSortDescriptor 的 NSFetchedResultsController