简体   繁体   English

如何使用 python 提取图像 url?

[英]How to extract image url with python?

I'm trying to extract image URLs from this code:我正在尝试从此代码中提取图像 URL:

<div class="theme-screenshot one attachment-theme-screenshot size-theme-screenshot wp-post-image loaded" data-featured-src="https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg" data-src="https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg" style='background-image: url("https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg");'></div>

How can I find the URLs in data-src?如何在 data-src 中找到 URL?

I'm using beautiful soup and find function but I have no idea how to extract links because I don't see img tag as usual...我正在使用漂亮的汤并找到 function 但我不知道如何提取链接,因为我没有像往常一样看到 img 标签...

Thank you for your time in advance提前感谢您的时间

You can try the following:您可以尝试以下方法:

from bs4 import BeautifulSoup

html = """
<div class="theme-screenshot one attachment-theme-screenshot size-theme-screenshot wp-post-image loaded" data-featured-src="https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg" data-src="https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg" style='background-image: url("https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg");'></div>
"""
soup = BeautifulSoup(html, "html.parser")
url = soup.select_one(
    "div.theme-screenshot.one.attachment-theme-screenshot.size-theme-screenshot.wp-post-image.loaded"
).get("data-src")

print(url)

This will return:这将返回:

https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg

Documentation for BeautifulSoup(bs4) can be found at: BeautifulSoup(bs4) 的文档可以在以下位置找到:

https://www.crummy.com/software/BeautifulSoup/bs4/doc/ https://www.crummy.com/software/BeautifulSoup/bs4/doc/

If you can't use an HTML parser for whatever reason, then you can use regex.如果您出于某种原因不能使用 HTML 解析器,那么您可以使用正则表达式。

import re

text = '''
<div class="theme-screenshot one attachment-theme-screenshot size-theme-screenshot wp-post-image loaded" data-featured-src="https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg" data-src="https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg" style='background-image: url("https://websitedemos.net/wp-content/uploads/2019/07/outdoor-adventure-02-home.jpg");'></div>
'''

parsed = re.search('(?<=data-src=").*(?=" )', text).group(0)

print(parsed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM