网页爬虫抓取百度图片(你检查下这个网页中的内容是不是通过js代码读取外部json数据来动态更新的)
优采云 发布时间: 2021-12-13 16:20网页爬虫抓取百度图片(你检查下这个网页中的内容是不是通过js代码读取外部json数据来动态更新的)
你通过js代码读取外部json数据来检查这个网页的内容是否动态更新。
请求只能获取网页的静态源代码,不能获取动态更新的内容。
对于动态更新的内容,使用 selenium 进行爬取。
或者通过F12控制台分析加载页面数据的链接,找到真正的json数据的地址进行爬取。
右键单击页面,在右键菜单中选择“查看网页源代码”。
这是网页的静态源代码。
如果本网页的静态源代码中有需要爬取的内容,则说明该页面没有动态内容,可以通过请求进行爬取。
否则就意味着页面内容是动态更新的,需要用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=©right=&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('抓取完成')
如果有帮助,希望采纳!谢谢!