美文网首页
python 学习一

python 学习一

作者: 八重代 | 来源:发表于2019-12-26 15:08 被阅读0次

    我学习python的目的很明确,就是为了学习爬虫,所以python的基础知识我基本没去看,都是在使用过程中遇到问题就去解决问题,我直接将自己学习的例子加上注释

    1、安装python

    我是直接百度看的,去官网下载安装包,用管理员的身份运行安装,记得一定要点击add path

    2、引入request

    在cmd里找到安装python的目录,然后找到Scripts下,运行命令pip install requests
    这样import requests就不会报错

    #使用之前需要使用cmd的命令,找到安装python的目录,找到scripts
    #执行命令pip install requests
    import requests
    
    #找到安装python的目录,pip install parsel
    from parsel import Selector
    #url = 'https://www.baidu.com'
    
    url = "http://quanben5.com/n/doupocangqiong/6.html"
    
    headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36"
    }
    
    #res = requests.get(url, headers=headers) # 爬取网站
    
    res = requests.get(url) # 爬取网站
    
    res.encoding = res.apparent_encoding # 设置编码
    
    html = res.text
    
    #print(html)
    
    #parsel  css选择器,提取网页数据结构
    
    sel = Selector(html)
    #获取的一章的标题
    title = sel.css('h1::text').get()
    #打开文件 创建文件
    # w以写方式打开,
    # a以追加模式打开 (从 EOF 开始, 必要时创建新文件)
    f=open(title+'.txt',mode='w',encoding='utf-8')
    #print(title)
    f.write(title)
    #content = sel.css('#content p::text').getall()
    #print(content)
    #获取的一章的内容
    for line in sel.css('#content p::text').getall():
        print(line,file=f)
    
    #关闭文件
    f.close()
    
    
    #定义函数
    def downloadone():
        print('3')
    
    
    #调用函数
    downloadone()
    

    相关文章

      网友评论

          本文标题:python 学习一

          本文链接:https://www.haomeiwen.com/subject/ochcoctx.html