import requests
from lxml import etree
import json
import os
# 设置Bing搜索URL和请求头
url = 'https://cn.bing.com/images/search?q=%E4%B8%80%E4%BA%BA%E4%B9%8B%E4%B8%8B%E5%9B%BE%E7%89%87&form=IQFRML&first=1&cw=1177&ch=693'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
}
# 发送GET请求获取Bing搜索结果页面的HTML内容
response = requests.get(url, headers=headers)
text = response.text
html = etree.HTML(text)
# 使用XPath选择器提取图片链接元素
images = html.xpath('//div[@class="dgControl waterfall"]/ul//a[@class="iusc"]')
# 创建一个列表来存储所有的图片URL
image_list = []
# 遍历图片链接元素,提取图片URL,并添加到列表中
for image in images:
image_url = image.xpath('.//@href')[0]
image_list.append(image_url)
# 检查文件是否已存在,如果存在则追加,否则创建新文件
file_path = 'image.json'
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
image_list.extend(existing_data)
# 写入图片URL到JSON文件中,并增加换行和缩进,提高可读性
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(image_list, f, ensure_ascii=False, indent=4)
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
image_list.extend(existing_data)
# 写入图片URL到JSON文件中,并增加换行和缩进,提高可读性
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(image_list, f, ensure_ascii=False, indent=4)
为什么保存的数据是乱码,而不是图片所对应的url呢?


在源代码中点击它时:
"/images/search?view=detailV2&ccid=O9QDSB5w&id=85EC8AC1C57E61CEB19D840B7E558C3A5D282DB0&thid=OIP.O9QDSB5wJ79blE2Go8ToQQHaNK&mediaurl=https%3a%2f%2fpic4.zhimg.com%2fv2-2230e311549f7d64e088d7752b375e75_r.jpg&exph=1920&expw=1080&q=%e4%b8%80%e4%ba%ba%e4%b9%8b%e4%b8%8b%e5%9b%be%e7%89%87&simid=608010036547625220&FORM=IRPRST&ck=815E7961C578C60D30E7AE51AED465AC&selectedIndex=0&itb=0"
会直动跳转到照片所对应的图片,当将鼠标反正这串乱码上会出现该图片说对应的网址。