鱼C论坛

 找回密码
 立即注册
查看: 1285|回复: 5

[已解决]aiohttp.ClientSession()的问题

[复制链接]
发表于 2021-8-30 17:44:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 江湖散人 于 2021-8-30 18:08 编辑
  1. import requests
  2. from lxml import etree
  3. import asyncio
  4. import aiohttp
  5. import aiofiles


  6. async def down_load(href, title):
  7.     async with aiohttp.ClientSession() as session:
  8.         async with session.get("https://www.17k.com" + href)as resp:
  9.             resp.encoding = "utf-8"
  10.             dic = await resp.text()
  11.             tree = etree.HTML(dic)
  12.             page_content = tree.xpath("/html/body/div[4]/div[2]/div[2]/div[1]/div[2]")[0]
  13.             lp = len(page_content) - 6
  14.             page_content = page_content[:lp]
  15.             for i in page_content:
  16.                 content = i.xpath("./text()")[0]
  17.                 async with aiofiles.open(("ibook/" + title), 'a', encoding='utf-8') as f:
  18.                     await f.write(content)


  19. async def get_page(url):
  20.     resp = requests.get(url)
  21.     resp.encoding = "utf-8"

  22.     tree = etree.HTML(resp.text)
  23.     dd = tree.xpath("/html/body/div[5]/dl/dd")[0]
  24.     task = []
  25.     for a in range(len(dd)):
  26.         href = dd[a].xpath("./@href")[0]
  27.         title = str(dd[a].xpath("./@title")[0]).split(":", 1)[0].replace("字数", "").replace("\r", "")
  28.         task.append(asyncio.create_task(down_load(href, title)))

  29.     await asyncio.wait(task)


  30. if __name__ == '__main__':
  31.     url = "https://www.17k.com/list/3318557.html"
  32.     loop = asyncio.get_event_loop()
  33.     loop.run_until_complete(get_page(url))
复制代码


这是一个运用异步协程来爬取网站小说的程序。
但是运行的时候老是报错:

dic = await resp.text()
return self._body.decode(encoding, errors=errors)  # type: ignore
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 400: character maps to <undefined>

爬取小说基本都下来了,只不过少了几章节。
不知道问题出在哪了。
哪位前辈帮忙看一下啊,谢谢啊!
最佳答案
2021-8-30 18:18:41
本帖最后由 2012277033 于 2021-8-30 18:46 编辑

你这个有几个问题,一个是解析时用的方法存在问题,需要用await关键字。
一个是文件写入存在问题,用的打开模式不对,如果是w的话,每次写入都是覆盖,最后只会记录到最后一行
还有一个编码问题:不确定是哪个编码直接ignore处理了.
修改了部分就这样:
  1. async def down_load(href, title):
  2.     async with aiohttp.ClientSession() as session:
  3.         async with session.get("https://www.17k.com" + href)as resp:
  4.             resp.encoding = "utf-8"
  5.             #这里resp.text()必须用await关键字来获取,后面加入编码格式这里直接跳过错误编码
  6.             tree = etree.HTML(await resp.text(errors="ignore"), parser=etree.HTMLParser(encoding='utf-8'))
  7.             page_content = tree.xpath(
  8.                     "/html/body/div[4]/div[2]/div[2]/div[1]/div[2]")
  9.             #跳过空白页
  10.             if page_content:
  11.                 page_content = page_content[0]
  12.             else:
  13.                 return
  14.             lp = len(page_content) - 6
  15.             page_content = page_content[:lp]
  16.             for i in page_content:
  17.                 #跳过空白行
  18.                 if i.xpath("./text()"):
  19.                     content = i.xpath("./text()")[0]
  20.                 else:
  21.                     continue
  22.                  #这里open的模式要用追加模式,不然最后只有最后一行被写入
  23.                 async with aiofiles.open(("ibook/" + title.replace(' ',"_")), 'a+', encoding='utf-8') as f:
  24.                     #这里末尾加个回车,保证每行都单独隔开
  25.                     await f.write(content+'\n')


  26. async def get_page(url):
  27.     resp = requests.get(url)
  28.     resp.encoding = "utf-8"

  29.     tree = etree.HTML(resp.text)
  30.     dd = tree.xpath("/html/body/div[5]/dl/dd")[0]
  31.     task = []
  32.     for a in range(len(dd)):
  33.         href = dd[a].xpath("./@href")[0]
  34.         title = str(dd[a].xpath("./@title")[0]).split(":",
  35.                                                       1)[0].replace("字数", "").replace("\r", "")
  36.         task.append(asyncio.create_task(down_load(href, title)))

  37.     await asyncio.wait(task)


  38. if __name__ == '__main__':
  39.     url = "https://www.17k.com/list/3318557.html"
  40.     loop = asyncio.get_event_loop()
  41.     loop.run_until_complete(get_page(url))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-8-30 18:18:41 | 显示全部楼层    本楼为最佳答案   
本帖最后由 2012277033 于 2021-8-30 18:46 编辑

你这个有几个问题,一个是解析时用的方法存在问题,需要用await关键字。
一个是文件写入存在问题,用的打开模式不对,如果是w的话,每次写入都是覆盖,最后只会记录到最后一行
还有一个编码问题:不确定是哪个编码直接ignore处理了.
修改了部分就这样:
  1. async def down_load(href, title):
  2.     async with aiohttp.ClientSession() as session:
  3.         async with session.get("https://www.17k.com" + href)as resp:
  4.             resp.encoding = "utf-8"
  5.             #这里resp.text()必须用await关键字来获取,后面加入编码格式这里直接跳过错误编码
  6.             tree = etree.HTML(await resp.text(errors="ignore"), parser=etree.HTMLParser(encoding='utf-8'))
  7.             page_content = tree.xpath(
  8.                     "/html/body/div[4]/div[2]/div[2]/div[1]/div[2]")
  9.             #跳过空白页
  10.             if page_content:
  11.                 page_content = page_content[0]
  12.             else:
  13.                 return
  14.             lp = len(page_content) - 6
  15.             page_content = page_content[:lp]
  16.             for i in page_content:
  17.                 #跳过空白行
  18.                 if i.xpath("./text()"):
  19.                     content = i.xpath("./text()")[0]
  20.                 else:
  21.                     continue
  22.                  #这里open的模式要用追加模式,不然最后只有最后一行被写入
  23.                 async with aiofiles.open(("ibook/" + title.replace(' ',"_")), 'a+', encoding='utf-8') as f:
  24.                     #这里末尾加个回车,保证每行都单独隔开
  25.                     await f.write(content+'\n')


  26. async def get_page(url):
  27.     resp = requests.get(url)
  28.     resp.encoding = "utf-8"

  29.     tree = etree.HTML(resp.text)
  30.     dd = tree.xpath("/html/body/div[5]/dl/dd")[0]
  31.     task = []
  32.     for a in range(len(dd)):
  33.         href = dd[a].xpath("./@href")[0]
  34.         title = str(dd[a].xpath("./@title")[0]).split(":",
  35.                                                       1)[0].replace("字数", "").replace("\r", "")
  36.         task.append(asyncio.create_task(down_load(href, title)))

  37.     await asyncio.wait(task)


  38. if __name__ == '__main__':
  39.     url = "https://www.17k.com/list/3318557.html"
  40.     loop = asyncio.get_event_loop()
  41.     loop.run_until_complete(get_page(url))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-30 18:47:23 | 显示全部楼层
2012277033 发表于 2021-8-30 18:18
你这个有几个问题,一个是解析时用的方法存在问题,需要用await关键字。
一个是文件写入存在问题,用的打 ...

大概就是这么处理。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-8-30 21:23:28 | 显示全部楼层
2012277033 发表于 2021-8-30 18:18
你这个有几个问题,一个是解析时用的方法存在问题,需要用await关键字。
一个是文件写入存在问题,用的打 ...

谢谢前辈,改完确实没问题了。
不过我有一个疑问,在存入文件的时候,你的 title 后边为什么要加一个替换啊?这是什么作用啊?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-31 10:01:35 | 显示全部楼层
江湖散人 发表于 2021-8-30 21:23
谢谢前辈,改完确实没问题了。
不过我有一个疑问,在存入文件的时候,你的 title 后边为什么要加一个替 ...

文章标题有空格,为了避免生成空格的文件名,一般我都是用下划线代替空格
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-8-31 10:34:42 | 显示全部楼层
2012277033 发表于 2021-8-31 10:01
文章标题有空格,为了避免生成空格的文件名,一般我都是用下划线代替空格

好的,谢谢啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-19 09:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表