Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix cannot identify image file <_io.BytesIO #2186

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions lncrawl/core/scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from bs4 import BeautifulSoup
from cloudscraper import CloudScraper, User_Agent
from PIL import Image
from PIL import Image, UnidentifiedImageError
from requests import Response, Session
from requests.exceptions import ProxyError
from requests.structures import CaseInsensitiveDict
Expand Down Expand Up @@ -239,17 +239,25 @@ def download_image(self, url: str, headers={}, **kwargs) -> Image:
"""Download image from url"""
if url.startswith("data:"):
content = base64.b64decode(url.split("base64,")[-1])
else:
headers = CaseInsensitiveDict(headers)
headers.setdefault("Origin", None)
headers.setdefault("Referer", None)
# headers.setdefault(
# "Accept",
# "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.9",
# )
return Image.open(BytesIO(content))

headers = CaseInsensitiveDict(headers)
headers.setdefault("Origin", None)
headers.setdefault("Referer", None)

try:
response = self.__process_request("get", url, headers=headers, **kwargs)
content = response.content
return Image.open(BytesIO(content))

except UnidentifiedImageError:
headers.setdefault(
"Accept",
"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.9",
)
response = self.__process_request("get", url, headers=headers, **kwargs)
content = response.content
return Image.open(BytesIO(content))
return Image.open(BytesIO(content))

def get_json(self, url, headers={}, **kwargs) -> Any:
"""Fetch the content and return the content as JSON object"""
Expand Down