开发者社区> 问答> 正文

python爬取糗事百科,该如何正确保存到本地文件夹?报错

我的程序已经可以爬取网络内容,但不太清楚怎么保存到当地文件夹,用网上方法试着做,但是有报错

import urllib
import urllib.request
import requests ##导入requests
from bs4 import BeautifulSoup ##导入bs4中的BeautifulSoup
import os


for i in range(35):
    page=i
    headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64)"}
    all_url = 'http://www.qiushibaike.com/hot/page/'+str(page)  ##开始的URL地址
    start_html = requests.get(all_url,headers=headers)
    Soup = BeautifulSoup(start_html.text, 'lxml')
    all_a = Soup.find('div', class_='col1').find_all(class_='content')
    for j in all_a:
        title = j.get_text() #取出a标签的文本
        path = str(title).strip()
        
        os.makedirs(os.path.join("C:\\Users\\DOU XIAOFEI\\Desktop\\wintercode\\funstory", path))
        os.chdir("C:\\Users\\DOU XIAOFEI\\Desktop\\wintercode\\funstory\\"+path) ##切换到上面创建的文件夹
        name = all_url[-9:-4]
        allurl = request.get(all_url,headers=headers)
        f = open(name + '.html', 'ab')
        f.write(allurl.content)
        f.close()



展开
收起
爱吃鱼的程序员 2020-06-08 20:07:56 492 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    报错发出来去掉路径中的空格试试i

    2020-06-08 20:08:14
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Improving Python and Spark Per 立即下载
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载