【问题标题】:How can I read and save an image from page with selenium, beautifulsoup and python 3?如何使用 selenium、beautifulsoup 和 python 3 从页面中读取和保存图像?
【发布时间】:2020-07-31 05:45:54
【问题描述】:

我的议程是我想在登录过程后保存来自网站的单个图像。检查后的图像返回具有/html/body/form/main/div/section/div[1]/div/div[2]/div/img 的完整xpath。我希望使用漂亮的汤或图像爬虫并将图像保存到变量中,然后使用 tesseract 从图像中提取文本。最近我一直在为 urllib、urllib.requests、selinium 的 x.path 读取图像而苦苦挣扎。我的想法是使用硒来保存图像,但没有找到任何结果。现在我需要编码部分的帮助,我想知道我是否可以将图像保存到变量中,以及 tesseract 是否可以从该变量访问该图像。下面给出了图像样本及其检查图像。 (检查的文本图像突出显示)。该表格只是一个示例,在现实生活中并不存在(至少我不知道知道一个)。任何帮助,将不胜感激。非常感谢。

图像1:

图片2:

【问题讨论】:

    标签: html css selenium-webdriver beautifulsoup tesseract


    【解决方案1】:

    你可以使用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 找到图像。

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2021-08-30
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2013-01-29
      • 1970-01-01
      相关资源
      最近更新 更多