&nbsp593 2021-07-01 21:05 采纳率: 100%
浏览 42
已采纳

爬虫读取文件乱码问题求解决

用爬虫爬图片读取文件里的中文乱码 求大佬解决,编码问题已经试过了gbk,utf-8,gb18030,不知道错哪里了,代码在下面,求求了。

import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import os

num = 0
numPicture = 0
file = ''
List = []

def Find(url, A):
    global List
    print('正在检测图片总数,请稍等......')
    t = 0
    i = 1
    s = 0
    while t < 1000:
        Url = url + str(t)
        try:
            Result = A.get(Url, timeout=7, allow_redirects=False)
        except BaseException:
            t = t + 60
            continue
        else:
            result = Result.text
            pic_url = re.findall('"objURL":"(.*?)",',result, re.S)
            s += len(pic_url)
            if len(pic_url) == 0:
                break
            else:
                List.append(pic_url)
                t =t + 60
    return s
def recommend(url):
    Re = []
    try:
        html = requests.get(url, allow_redirects=False)
    except error.HTTPError as e:
        return
    else:
        html.encoding = 'utf-8'
        bsObj = BeautifulSoup(html.text,'html.parser')
        div = bsObj.find('div', id='topRS')
        if div is not None:
            listA = div.findAll('a')
            for i in listA:
                if i is not None:  
                    Re.append(i.get_text())
        return Re
def dowmloadPicture(html, keyword):
    global num
    pic_url = re.findall('"objURL":"(.*?)",',html, re.S)
    print('找到关键词:' +keyword + '的图片,即将开始下载图片...')
    for each in pic_url:
        print('正在下载第' + str(num+1) + '张图片,图片地址:'+ str(each))
        try:
          if each is not None:
            pic = requests.get(each, timeout=7)
          else:
            continue
        except BaseException:
            print('错误,当前图片无法下载')
            continue
        else:
            string = file + r'\\' + keyword + '_' + str(num) + '.jpg'
            fp = open(string, 'wb')
            fp.write(pic.content)
            fp.close()
            num +=1
        if num>=numPicture:
            return
if __name__== '__main__':
    headers = {
    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
    'Upgrade-Insecure-Requests': '1'
  }
    A = requests.Session()
    A.headers = headers
    tm = int(input('请输入每类图片的下载数量 '))
    numPicture = tm
    line_list = []
    with open('./name.txt', encoding='gb18030') as file:
        line_list = [k.strip() for k in file.readlines()] 
    for word in line_list:
        url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='
        tot = Find(url, A)
        Recommend = recommend(url)
        print('经过检测%s类图片共有%d张' % (word, tot))
        file = word + '文件'
        y = os.path.exists(file)
        if y == 1:
          print('该文件已存在,请重新输入')
          file = word + '文件夹2'
          os.mkdir(file)
        else:
          os.mkdir(file)
        t = 0
        tmp = url
        while t < numPicture:
          try:
            url = tmp + str(t)
            result = A.get(url, timeout=10, allow_redirects=False)
            print(url)
          except error.HTTPError as e:
            print('网络错误,请调整网络后重试')
            t = t + 60
          else:
            dowmloadPicture(result.text, word)
            t = t + 60
    print('当前搜索结束,感谢使用')

img

img

img

  • 写回答

3条回答 默认 最新

  • Roc-xb 后端领域优质创作者 2021-07-01 21:19
    关注
      with open('./name.txt', encoding='utf-8') as file:
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵