这段代码可能会报错的原因是:缺少必要的库或库版本不匹配。

需要确保已安装requests和bs4库,并且版本是最新的。可以使用以下命令安装或更新库:

pip install requests
pip install beautifulsoup4

另外,如果使用的是Python2.x版本,需要将print语句改为print函数,例如:

print(f"获取网页内容出错:{e}")

改为:

print('获取网页内容出错:' + str(e))

如果仍然报错,请检查代码是否完整,以及代码路径是否正确。

代码示例:

import requests
from bs4 import BeautifulSoup
import os
import threading

# 网页链接
url = 'https://www.vcg.com/creative'

# 获取网页内容
try:
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
except Exception as e:
    print('获取网页内容出错:' + str(e))
    exit()

# 获取所有图片标签
img_tags = soup.find_all('img')

# 创建文件夹(如果不存在)
folder_path = 'D:/pt'
if not os.path.exists(folder_path):
    os.makedirs(folder_path)

# 去重集合
url_set = set()

# 下载图片函数
def download_img(img_url, file_path):
    try:
        img_data = requests.get(img_url).content
        with open(file_path, 'wb') as f:
            f.write(img_data)
    except Exception as e:
        print('下载图片 ' + img_url + ' 出错:' + str(e))

# 遍历所有图片标签,获取图片 URL,并保存到本地
threads = []
for img in img_tags:
    img_url = img.get('src')
    if img_url and 'http' in img_url and img_url not in url_set:
        url_set.add(img_url)
        file_name = img_url.split('/')[-1]
        file_path = os.path.join(folder_path, file_name)
        thread = threading.Thread(target=download_img, args=(img_url, file_path))
        threads.append(thread)
        thread.start()
Python爬虫代码报错:ImportError: No module named 'requests' 或 'bs4'

原文地址: https://www.cveoy.top/t/topic/n23K 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录