【发布时间】:2021-04-22 16:24:01
【问题描述】:
我创建了以下 python 脚本来从指定的 url 中提取图像 src 路径:
from requests_html import HTMLSession
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
url="https://www.example.com/"
session = HTMLSession()
r = session.get(url)
b = requests.get(url)
soup = BeautifulSoup(b.text, "lxml")
images = soup.find_all('img')
for img in images:
if img.has_attr('src'):
print(img['src'])
脚本运行良好,但我们使用 CDN,所以一些图像路径类似于:
https://i2.wp.com/www.example.com/wp-content/uploads/2020/06/image-name.png?fit=250%2C250&ssl=1
所以,我希望能够排除某些以 https://i2.wp.com 开头的图像 src 路径(可能是正则表达式),例如:
url="https://www.example.com/"
exclude=".*https://i2.wp.com"
images = soup.find_all('img')
for img in images:
if not ** something here to ignore excluded image src urls **:
if img.has_attr('src'):
print(img['src'])
这可能吗?
谢谢
【问题讨论】:
-
拼写为
.startswith(...),例如if img['src'].startswith("https://i2.wp.com/"): ...
标签: python beautifulsoup python-requests