python获取bing搜索图片

python获取bing搜索图片

直接贴代码:

from lxml import etree
import requests

name = input("请输入想要查找的图片类型:")
num = int(input("请输入抓取页数数目:"))
header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203"}
img_set = set()
for i in range(1, num + 1):
    url = f"https://cn.bing.com/images/async?q={name}&first={i}&count=100&cw=1177&ch=938&relp=35&datsrc=I&layout=ColumnBased&apc=0&mmasync=1&dgState=c*6_y*1664s1912s1975s1789s1831s1804_i*36_w*186&IG=A6460BCE95654EA3990CEED39809611F&SFX=2&iid=images.5562"
    html = requests.get(url, headers=header)
    html.encoding = html.apparent_encoding
    html = html.text
    img = etree.HTML(html)
    img = img.xpath("//img/@src")
    img_set.update(img)
print(f"已抓取{name}图片{len(img_set)}张,正在本地化中")
img_list = list(img_set)
count = 0
for i in img_list:
    count += 1
    response = requests.get(i).content
    with open(f"D:/{name}/{count}.jpg", "wb") as f:
        f.write(response)

发群里表示大功告成,大佬发现代码还能在精简优化,贴出大佬苏晓晴 - 我的生活记录 (toubiec.cn) 的代码:

import requests
from lxml import etree
from pathlib import Path

name = input("请输入想要查找的图片类型:")
num = int(input("请输入抓取页数数目:"))

header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203"}

def build_url(name, page):
    return f"https://cn.bing.com/images/async?q={name}&first={page}&count=100&cw=1177&ch=938&relp=35&datsrc=I&layout=ColumnBased&apc=0&mmasync=1&dgState=c*6_y*1664s1912s1975s1789s1831s1804_i*36_w*186&IG=A6460BCE95654EA3990CEED39809611F&SFX=2&iid=images.5562"

img_set = {img for i in range(1, num + 1) for img in etree.HTML(requests.get(build_url(name, i), headers=header).text).xpath("//img/@src")}

print(f"已抓取{name}图片{len(img_set)}张,正在本地化中")

for count, img_url in enumerate(img_set, start=1):
    response = requests.get(img_url).content
    file_path = Path(f"D:/{name}/{count}.jpg")
    file_path.write_bytes(response)

然后发现其实bing的图都是缩略图,没啥用,只能当学习学习python.