如何使用 selenium、beautifulsoup 和 python 3 从页面读取和保存图像?
How can I read and save an image from page with selenium, beautifulsoup and python 3?
我的议程是我想在登录程序后保存来自网站的单个图像。检查 returns 后的图像具有 /html/body/form/main/div/section/div[1]/div/div[2]/div/img
的完整 xpath。我希望使用漂亮的汤或图像爬虫并将图像保存到变量,然后使用 tesseract 从图像中提取文本。最近我一直在与 urllib、urllib.requests、selinium 的读取图像 x.path 作斗争。我的想法是使用selenium来保存图像但没有找到任何结果。现在我需要编码部分的帮助,我想知道我是否可以将图像保存到变量以及 tesseract 是否可以从该变量访问该图像。下面给出了图像样本及其检查图像。 (检查的文本图像突出显示)。该表格只是一个示例,在现实生活中并不存在(至少我不知道知道一个)。任何帮助,将不胜感激。非常感谢。
图片 1:
图2:
您可以使用urllib来保存图片
import urllib
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(WEBSITE_URL)
# get the image
img = driver.find_element_by_xpath('/html/body/form/main/div/section/div[1]/div/div[2]/div/img')
src = img.get_attribute('src')
# download the image
urllib.request.urlretrieve(src, "img.png")
这会将图像保存到工作目录中的 img.png 文件中,然后您可以使用图像处理和 tesseract 从中提取文本。我不建议使用静态 XPATH 来查找图像,因为如果网站所有者更改网站上的任何内容,它可能会发生变化,相反,您应该使用这个:
img = driver.find_element_by_id("ContentPlaceHolder1_Imgquestions")
,
这样即使网站布局发生变化,您仍然可以通过其 ID 找到图片。
我的议程是我想在登录程序后保存来自网站的单个图像。检查 returns 后的图像具有 /html/body/form/main/div/section/div[1]/div/div[2]/div/img
的完整 xpath。我希望使用漂亮的汤或图像爬虫并将图像保存到变量,然后使用 tesseract 从图像中提取文本。最近我一直在与 urllib、urllib.requests、selinium 的读取图像 x.path 作斗争。我的想法是使用selenium来保存图像但没有找到任何结果。现在我需要编码部分的帮助,我想知道我是否可以将图像保存到变量以及 tesseract 是否可以从该变量访问该图像。下面给出了图像样本及其检查图像。 (检查的文本图像突出显示)。该表格只是一个示例,在现实生活中并不存在(至少我不知道知道一个)。任何帮助,将不胜感激。非常感谢。
图片 1:
图2:
您可以使用urllib来保存图片
import urllib
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(WEBSITE_URL)
# get the image
img = driver.find_element_by_xpath('/html/body/form/main/div/section/div[1]/div/div[2]/div/img')
src = img.get_attribute('src')
# download the image
urllib.request.urlretrieve(src, "img.png")
这会将图像保存到工作目录中的 img.png 文件中,然后您可以使用图像处理和 tesseract 从中提取文本。我不建议使用静态 XPATH 来查找图像,因为如果网站所有者更改网站上的任何内容,它可能会发生变化,相反,您应该使用这个:
img = driver.find_element_by_id("ContentPlaceHolder1_Imgquestions")
,
这样即使网站布局发生变化,您仍然可以通过其 ID 找到图片。