从多个URL提取图像

2024-04-19 01:21:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过一个URL列表进行迭代,并从每个页面提取图像。但是,在某些情况下,图像不存在,并且url与我通常观察到的url模式不同。你知道吗

例如,当我遇到这样一个url时,我所拥有的代码- 我收到一条错误信息

这是我写的代码:

file = pd.read_csv(path)
for index,row in file.iterrows():
    site = row['link']
    response = requests.get(site)
    soup = BeautifulSoup(response.text, 'html.parser')
    pics = soup.find('img')
    pic_url = pics['src']
    urllib.request.urlretrieve(pic_url,'C:\\Users\\User\\test\\pictures\\'+ str(site.split('/')[-1])+'.jpg')

这是我的数据样本

name            link
 one            https://boxrec.com/en/proboxer/844760
 two            https://boxrec.com/en/proboxer/838706
 three          https://boxrec.com/en/proboxer/879108
 four           https://boxrec.com/en/proboxer/745266

这是我的错误信息

ValueError: unknown url type: '/build/images/main/avatar.jpeg'

更新: 我尝试添加try,除了捕获错误并继续。然而,我开始得到错误信息

TypeError: 'NoneType' object is not subscriptable

然后我更新了我的代码

try:
         pic_url = pics['src']
except:
         image = 'https://chapters.theiia.org/central-mississippi/About/ChapterOfficers/_w/person-placeholder_jpg.jpg'
         urllib.request.urlretrieve(image,'C:\\Users\\User\\test\\pictures\\'+str(site.split('/')[-1])+'.jpg')
try:
        urllib.request.urlretrieve(pic_url,'C:\\Users\\User\\test\\pictures\\'+ str(site.split('/')[-1])+'.jpg')
except:
        image = 'https://chapters.theiia.org/central-mississippi/About/ChapterOfficers/_w/person-placeholder_jpg.jpg'
        urllib.request.urlretrieve(image,'C:\\Users\\User\\test\\pictures\\'+str(site.split('/')[-1])+'.jpg')

但这会返回多次重复,在某些情况下,id的空白图片实际上存在


Tags: httpstesturlrequestsiteurllibusersjpg
3条回答

只要简单地把它放在一个带有for循环的try/except块中,就可以在每个异常情况下继续执行列表中的下一项

file = pd.read_csv(path)
for index,row in file.iterrows():
    site = row['link']
    try:
       response = requests.get(site)
       soup = BeautifulSoup(response.text, 'html.parser')
       pics = soup.find('img')
       pic_url = pics['src']
       urllib.request.urlretrieve(pic_url,'C:\\Users\\User\\test\\pictures\\'+ str(site.split('/')[-1])+'.jpg')
    except Exception:
            continue

因为“/build/images/main”/化身.jpeg“是亲戚吗路径。它是可以过滤的默认化身出去。如果你不想过滤掉它,你可以把它转换成完整的路径。路径以下代码包括自动转换功能。 下面的代码使用库简化的\u scrapy

from simplified_scrapy.simplified_doc import SimplifiedDoc 
file = pd.read_csv(path)
for index,row in file.iterrows():
    site = row['link']
    response = requests.get(site)
    doc = SimplifiedDoc(response.text)
    pics = doc.listImg(url=site)[0]
    pic_url = pics.url
    urllib.request.urlretrieve(pic_url,'C:\\Users\\User\\test\\pictures\\'+ str(site.split('/')[-1])+'.jpg')

如果您只是想避免错误并继续使用其他有效的图像,可以将其括在try: except: continue

像这样的

try:
    urllib.request.urlretrieve(...)
except ValueError:
    continue

相关问题 更多 >