【发布时间】:2020-12-07 18:01:26
【问题描述】:
我编写了一个程序,该程序使用 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 个结果,我怎样才能增加这个数字?
【问题讨论】:
-
嗨,为什么在这种情况下你必须使用 Selenium?在您的示例中,我无法找到 Selenium 的用例。您能否提供有关您要实现的目标的更多详细信息? Selenium 的主要用途是以“最终用户”的方式与浏览器交互。在这里我看到你只需要调用http get请求并解析返回的html。
-
@PiotrM。第一个原因是,在 Bing 或 Google 的图像引擎上搜索时,您看到的不是实际图像,而是它的一个小版本,要获得实际图像,您需要单击它,而 BeatifulSoup 无法做到这一点。第二个原因是,当使用 BeatifulSoup 解析
标记时,我得到 14 个结果,而使用 Selenium 我得到 35 个结果,虽然不算多,但至少是这样。
-
好的,谢谢 - 你没有提供这种交互的任何实现/伪代码,所以我不确定你是否真的需要 Selenium。 1) 只有 35 个结果 - 您是否向下滚动页面?因为页面滚动后会动态添加结果 2) GIF 文件有什么问题?你能提供更多细节吗?
-
@PiotrM。 1)这就是结果量的问题,谢谢。 2) 您知道在搜索图像时如何使用多个过滤器(图像大小、颜色、类型等)。如何访问这些选项并进行编辑?
-
好的。因此您必须找到过滤器元素并与它们交互(单击),例如类型过滤器的 css 选择器可能如下所示:“span[title='Type filter']” 当您单击位于此定位器的元素时,您必须找到要过滤的类型 - 对于 GIF,它可以是 css 选择器[title='动画 GIF']
标签: python selenium microsoft-edge