繁体   English   中英

如何使用 Python 的 BeautifulSoup html 解析器获取具有 2 个“src”属性的 img 标签 src

[英]How to use Python's BeautifulSoup html parser to get img tag src with 2 'src' attributes

我有 HTML 页面,其中包含具有 2 个“src”属性的图像标签,我想使用 BS 来提取第一个“src”而不是第二个“src”。

例如:

当我按如下方式使用BS时:

from bs4 import BeautifulSoup

html_doc = <img class="lazy" src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=980:*"                        src="https://www.mdf.qa/media/catalog/product/cache/1/image/800x800/9df78eab33525d08d6e5fb8d27136e95/b/l/black_2.jpg"/>

soup = BeautifulSoup(html_doc, 'html.parser')
bs_images = soup.find_all('img')
for bs_image in bs_images:
   attrs = bs_image.attrs
   image_path = attrs['src']

我得到的路径是第二个src“ https://www.mdf.qa/media/catalog/product/cache/1/image/800x800/9df78eab33525d08d6e5fb8d27136e95/b/l/black_2.jpg ”但我需要第一个src - https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh; 0,0.190xh&resize=980 :*.

似乎 BeautifulSoup 正在重写第一个 src 顶部的第二个 src,因此第一个 src 不会存储在任何地方。 我建议使用正则表达式来解决这个问题。

import re

html_doc = '<img class="lazy" src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=980:*"                        src="https://www.mdf.qa/media/catalog/product/cache/1/image/800x800/9df78eab33525d08d6e5fb8d27136e95/b/l/black_2.jpg"/>'

bs_images = re.findall('<img[^<>]+>', html_doc)
for bs_image in bs_images:
   image_path = re.search('src="([^"]+)"', bs_image).group(1)
   print(image_path)

是 src 匹配的链接。 使用 re.search 我们只得到第一个匹配项(使用 findall 我们会得到所有匹配项)。

暂无
暂无

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

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