我编写了一个程序,该程序使用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个结果,如何增加该数字?
有两种添加搜索过滤器的方法。
如果要添加搜索过滤器,可以在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()
对于搜索结果号,我没有找到更改它的选项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句