关于#python#的问题:python爬虫爬取百度图片

 ###### 问题遇到的现象和发生背景
想要爬取百度上的图片,爬取不出来
 ###### 问题相关代码,请勿粘贴截图

import requests
import urllib.request
from bs4 import BeautifulSoup
import os
import time

url = 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%C6%A4%BF%A8%C7%F0'
headers = {'User-Agent': 'Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KETTLE, like '
                         'Gecko) Chrome/34.0.1847.137 Safari/537.36 LOBBERS'}
response = requests.get(url, headers=headers)  # 使用headers避免访问受限
soup = BeautifulSoup(response.content, 'html.parser')
items = soup.find_all('img')
folder_path = './photo/'
if not os.path.exists(folder_path):  # 判断文件夹是否已经存在
    os.makedirs(folder_path)  # 创建文件夹

for index, item in enumerate(items):
    if item:
        html = requests.get(item.get('src'))  # get函数获取图片链接地址,requests发送访问请求
        img_name = folder_path + str(index + 1) + '.png'
        with open(img_name, 'wb') as file:  # 以byte形式将图片数据写入
            file.write(html.content)
            file.flush()
        file.close()  # 关闭文件
        print('第%d张图片下载完成' % (index + 1))
        time.sleep(1)  # 自定义延时
print('抓取完成')

 ###### 运行结果及报错内容

img

你检查下这个网页中的内容是不是通过js代码读取外部json数据来动态更新的。
requests只能获取网页的静态源代码,动态更新的内容取不到。
对于动态更新的内容要用selenium 来爬取。

或者是通过F12控制台分析页面数据加载的链接,找到真正json数据的地址进行爬取。

在页面上点击右键,右键菜单中选 "查看网页源代码"。

img


这样看到的才是网页的静态源代码。
如果这个网页的静态源代码中有你需要爬取的内容,就说明该页面没有动态内容,可以用requests爬取。
否则就说明该页面的内容是动态更新的,要用selenium 来爬取.

你题目的解答代码如下:

import requests
import urllib.request
from bs4 import BeautifulSoup
import os
import time
url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=11169489735361612176&ipn=rj&ct=201326592&is=&fp=result&fr=&word=%E7%9A%AE%E5%8D%A1%E4%B8%98&queryWord=%E7%9A%AE%E5%8D%A1%E4%B8%98&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&expermode=&nojc=&isAsync=&pn=30&rn=30&gsm=1e&1638026359917='
headers = {
'Host': 'image.baidu.com',
'Pragma': 'no-cache',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'
}
response = requests.get(url, headers=headers)  # 使用headers避免访问受限
print(response.json())
items = response.json()['data']
folder_path = './photo/'
if not os.path.exists(folder_path):  # 判断文件夹是否已经存在
    os.makedirs(folder_path)  # 创建文件夹
for index, item in enumerate(items):
    if item:
        print(item['middleURL'])
        html = requests.get(item['middleURL'])  # get函数获取图片链接地址,requests发送访问请求
        img_name = folder_path + str(index + 1) + '.png'
        with open(img_name, 'wb') as file:  # 以byte形式将图片数据写入
            file.write(html.content)
            file.flush()
        file.close()  # 关闭文件
        print('第%d张图片下载完成' % (index + 1))
        time.sleep(1)  # 自定义延时
print('抓取完成')

img

如有帮助,望采纳!谢谢!

当前静态页面的图片,在headers中添加cookie,用你提供的代码稍作修改即可获取:

import requests
import urllib.request
from bs4 import BeautifulSoup
import os
import time
url = 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%C6%A4%BF%A8%C7%F0'
headers = {'User-Agent': 'Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KETTLE, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LOBBERS', 'Cookie': 'ZD_ENTRY=bing; BAIDUID=7DE12BE8CD0103334847D14C4C594E4A:FG=1; __yjs_duid=1_5b7eda75a7c6f418b6f22766d1353b701636439185927; BIDUPSID=7DE12BE8CD0103334847D14C4C594E4A; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; userFrom=null; ab_sr=1.0.1_ZDUzNDA0MWIxNTYxYTM3YzIzZTY0MzcxODFhNjQ1MzBiODAzZDM5ZWZjM2Q1MWY5NzUwYTY5MWRjZjRhY2JlZWE4OTU5MTQ3ZDg1Y2U4YjllNjM4NDliYTc3ZjFmN2EyN2NlMGYyNmE2ODBiMjMyOGY1MzI0YjM2ZjQ5NTgxZGNlNTExNDcyYTJjYzRkNjFhNjBhMDcxOTE2N2NhODcwMg=='}
response = requests.get(url, headers=headers)  # 使用headers避免访问受限
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.find_all('img')
print(items)
folder_path = './imgs1'
if not os.path.exists(folder_path):  # 判断文件夹是否已经存在
    os.makedirs(folder_path)  # 创建文件夹
for index, item in enumerate(items):
    if item:
        print(item.get('src'))
        if item.get('src').endswith(('.png','gif','jpg')):
            html = requests.get('https:'+item.get('src'))  # get函数获取图片链接地址,requests发送访问请求
            x = item.get('src')[-4:]
            img_name = folder_path +'/' +str(index + 1) + x
            with open(img_name, 'wb') as file:  # 以byte形式将图片数据写入
                file.write(html.content)
                file.flush()
                print('第%d张图片下载完成' % (index + 1))
                time.sleep(1)  # 自定义延时
print('抓取完成')


对于页面上动态加载的图片需用selenium获取。