鱼C论坛

 找回密码
 立即注册
查看: 1116|回复: 6

[已解决]异步爬取文件写入问题

[复制链接]
发表于 2021-12-14 11:38:44 | 显示全部楼层 |阅读模式
20鱼币
异步的写法应该没有问题。已经能创建文件了,但是应该是写入部分出了问题。创建的文件没有写入操作,里面内容是空,写入时有报错。请指导。附源码

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import aiohttp
  4. import aiofiles
  5. import asyncio
  6. import bs4
  7. import re
  8. from lxml import html

  9. def getHtml(url,headers):
  10.     try:
  11.         r = requests.get(url,headers)
  12.         r.raise_for_status()
  13.         r.encoding = r.apparent_encoding
  14.         return r.text
  15.     except Exception as e:
  16.         print("访问页面有误!",e)
  17.         return ""

  18. def getChater(html):
  19.     domain = "https://www.bbiquge.net/book_84680/"
  20.     resultls = {}
  21.     gcbs = BeautifulSoup(html,"html.parser")
  22.     for dd in  gcbs.find('div',class_="zjbox").dl:  #章节内容对应的标签
  23.         if isinstance(dd,bs4.element.Tag):
  24.             if dd.name == "dd" and dd.string != None:
  25.                 #print(dd.a.string,dd.a.get("href"))   
  26.                 resultls[dd.a.string]=domain + dd.a.get("href")      #返回章节名及链接
  27.     return resultls


  28.             
  29. async def getContent(url,filename):   #传过来的字典是 章节名:链接
  30.     async with aiohttp.ClientSession() as session:
  31.         async with session.get(url) as resp:
  32.             html =await resp.text()
  33.             # bs = BeautifulSoup(html,"html.parser").find("div",id="content")
  34.             # content = bs.find("div",id="content")
  35.             async with open(filename+".txt","w",encoding="utf-8") as f:
  36.                 await f.write(BeautifulSoup(html,"html.parser").find("div",id="content").text.replace('\xa0'*4,'\n\n       '))  #处理符号,整理格式
  37.             print("done!"+filename)
  38.             
  39.       
  40.             

  41. async def main():
  42.     url = "https://www.bbiquge.net/book_84680/"
  43.     headers = {
  44.         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36 Edg/96.0.1054.53"
  45.     }
  46.     html = getHtml(url,headers)
  47.     #获得 章节名及链接
  48.     resultls = getChater(html)
  49.     # 异步下载章节内容
  50.     tasks = []
  51.     for item in resultls.items():
  52.         tasks.append(asyncio.create_task(getContent(item[1],item[0])))
  53.     await asyncio.wait(tasks)   
  54.    
  55. if __name__ == "__main__":
  56.     loop =  asyncio.new_event_loop()
  57.     asyncio.set_event_loop(loop)
  58.     loop.run_until_complete(main())
复制代码
最佳答案
2021-12-14 11:38:45

python 本身就是同步的,并不擅长处理异步问题,(异步我也不懂)

所以,很想知道你的动机   是练习用吗 否则 同步爬取就可以啦

最佳答案

查看完整内容

python 本身就是同步的,并不擅长处理异步问题,(异步我也不懂) 所以,很想知道你的动机 是练习用吗 否则 同步爬取就可以啦
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-12-16 11:59:30 | 显示全部楼层
open时改用,aiofiles.open  解决了
但是新的问题是爬到后面好像有编码问题无法解析,估计是aiohttp库的问题
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-12-14 11:38:45 | 显示全部楼层    本楼为最佳答案   

python 本身就是同步的,并不擅长处理异步问题,(异步我也不懂)

所以,很想知道你的动机   是练习用吗 否则 同步爬取就可以啦
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-12-14 15:29:05 | 显示全部楼层
自顶
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-12-15 08:46:01 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-12-15 10:07:06 | 显示全部楼层
wp231957 发表于 2021-12-15 10:04
python 本身就是同步的,并不擅长处理异步问题,(异步我也不懂)

所以,很想知道你的动机   是练习用 ...

异步爬取的效率更高,更多情况需要异步协程跟多线程结合,这个我自己发现问题了。是我导了包忘记用了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-12-15 10:12:39 | 显示全部楼层
specail 发表于 2021-12-15 10:07
异步爬取的效率更高,更多情况需要异步协程跟多线程结合,这个我自己发现问题了。是我导了包忘记用了{:10 ...

我还以为是异步往同一个文件里面写,脑海中重在构思上次看到的资料,python目前不支持文件锁。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-1 19:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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