为了账号安全,请及时绑定邮箱和手机立即绑定

Python开发简单爬虫

蚂蚁帅帅 全栈工程师
难度初级
时长 1小时14分
学习人数
综合评分9.67
646人评价 查看评价
9.9 内容实用
9.6 简洁易懂
9.5 逻辑清晰
  • Python UnicodeEncodeError: 'gbk' codec can't encode character 解决方法 使用的python3.5,在window下,我在调试的时候遇到里编码出错的问题,找了很久,终于解决里。这此分享出来,给可能遇到同样问题的同学。 当把抓取出来的内容显示在网页上时,这个地方是出错的关键点。在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析我们的网络数据流txt,然而txt此时已经是decode过的unicode编码,这样的话就会导致解析不了,出现问题。应写为: fout = open('output.html','w',encoding='utf-8') 同时在html中声明Python
    查看全部
    3 采集 收起 来源:HTML输出器

    2016-03-09

  • 使用ctrl+1快捷添加方法时,添加的不对是怎么回事。。。
    查看全部
    3 采集 收起 来源:调度程序

    2016-02-14

  • 爬虫调度器:启动、停止、监视爬虫运行情况; URL管理器:将要爬取的URL和已经爬取的URL 网页下载器:URL管理器将将要爬取的URL传送给网页下载器下载下来; 网页解析器:将网页下载器下载的网页的内容传递给网页解析器解析; (1)、解析出新的URL传递给URL管理器; (2)、解析出有价值的数据; 上面三个形成了一个循环,只要网页解析器有找到新的URL,就一直执行下去;
    查看全部
  • python3:

    from urllib import request as urllib2
    import http.cookiejar as cookielib

    url = 'https://www.baidu.com'
    # 第一种
    response1 = urllib2.urlopen(url)
    print(response1.getcode())
    # 第二种
    request = urllib2.Request(url)
    request.add_header('user-agent','Mozilla/5.0')
    response2 = urllib2.urlopen(url)
    print(response2.getcode())
    # 第三种
    cookie = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    urllib2.install_opener(opener)
    response3 = urllib2.urlopen(url)
    print(response3.getcode())

    查看全部
  • class UrlManager(object):
       
        def __init__(self):
            """URL管理器需要维护两个列表,①待爬取的URL列表new_urls;②已爬取的URL列表old_urls"""
            self.new_urls = set()
            self.old_urls = set()
       
        def add_new_url(self,url):
            """ 向管理器中添加一个新的URL,"""
            if url is None:             #如果URL为空,不进行添加
                return
            if url not in self.new_urls and url not in self.old_urls:
                self.new_urls.add(url)  #如果URL就没在待爬取的URL列表里面,又没在已爬取的URL列表里面,将其添加到待爬取的URL列表中
         
        def add_new_urls(self,urls):
            """ 向管理器中添加批量的URL"""
            if urls is None or len(urls)==0:
                return                  #如果URL列表不存在或为空,不进行添加
            for url in urls:
                self.add_new_url(url)   #如果存在,单个添加到待爬取的URL
        
        def has_new_url(self):
            """判断管理器中是否有新的URL"""
            return len(self.new_urls)!=0        #如果new_url列表部位空,就说明还有待爬取的URL,

        def get_new_url(self):
            """从URL管理器中获取一个新的待爬取的URL"""
            new_url = self.new_urls.pop()       #获取一个待爬取的URL,pop会讲待爬取的URL取出,然后移除该URL
            self.old_urls.add(new_url)          #将这个待爬取的URL添加到已爬取的URL列表
            return new_url

    查看全部
    3 采集 收起 来源:URL管理器

    2018-12-05

  • from baike_spider import html_downloader, html_outputer, url_manager
    from lxml.html import html_parser
    from astropy.units import count

    class SpiderMain(object):
        """爬虫总调度程序,会使用HTML的下载器,解析器,输出器来完成功能"""
        def __init__(self):
            """在构造函数中初始化所需要的各个对象"""
            self.urls = url_manager.UrlManager()                  #URL管理器
            self.downloader = html_downloader.HtmlDownloader()    #URL下载器
            self.parser = html_parser.HtmlParser()                #URL解析器
            self.output = html_outputer.HtmlOutputer()            #URL输出器
       
        def craw(self,root_url):
            """爬虫的调度程序,root_url就是入口url,将其添加到URL管理器"""
            count = 1
            self.urls.add_new_url(root_url)                            #添加一个新的未爬取的URL
            while self.urls.has_new_url():
                try:
                    """设置一个异常处理,用来处理网页中已经失效的URL和空的URL"""
                    new_url = self.urls.get_new_url()                  #获取一个待爬取的URL
                    print("crow %d: %s"%(count,new_url))
                    html_cont = self.downloader.download(new_url)      #下载URL页面
                    new_urls, new_data =self.parser.parse(new_url,html_cont)   
                    #调用解析器解析页面数据,得到新的URL列表和新的数据,传入两个参数,传入该URL,和下载的数据
                    self.urls.add_new_urls(new_urls)                   #新的URL列表补充到URLS
                    self.output.collect_data(new_data)                 #收集数据
                   
                    if count == 100:
                        """设置一个循环控制URL的爬取个数"""
                        break
                   
                    count  += 1
                except:
                    print("craw failed")
            self.outputer.output_html()

    if __name__ == '__main__':
        root_url = "http://baike.baidu.com/view/21087.html"       #爬虫入口URL
        obj_spider = SpiderMain()      #调用主函数
        obj_spider.craw(root_url)      #启动爬虫

    查看全部
    3 采集 收起 来源:调度程序

    2018-12-05

  • soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')

    在python3中,默认为UTF-8,报错去掉

    from_encoding='utf-8'

    就行

    查看全部
  • 现在百度的是https加密方式的了,而且目录结构也变了,所以写的时候要改一下
    比如使用Request对象
    response = urllib2.urlopen(request,context = context)
    页面解析的话可以
    links = soup.findAll('a',href=re.compile(r"/item/"))
    这样子就能匹配到了

    查看全部
  • 【2017/10/12】【Python3.6.2】【PyCharm 2017.2】【Chrome】 1 . IDE中文输出;HTML文档中文显示; a . IDE中文输出; 在spider_main.py中, 源码:print('craw %d:%s' % (count, new_url)) 修改:print('craw %d : %s' % (count, urllib.parse.unquote(new_url,encoding='utf-8'))) 记得要 import urllib.parse b . HTML文档中文显示; 在html_outputer.py中, 有两个地方: α:文件打开位置 源码:fout = open('output.html','w') 修改:fout = open('output.html','w', encoding='utf-8') β:HTML代码中,看到有人建议加:fout.write("<head><meta http-equiv='content-type' content='text/html;charset=utf-8'></head>"),实际上在本人实验中,加入与否并没有实质变化,本人建议如下: (1). 在课堂源码基础上,将data['title'].encode('utf-8)去掉,并在url的td标签后添加urllib.parse.unquote(data['url'],encoding='utf-8') 2 . URL匹配; new_full_url = urllib.parse.urljoin(page_url, new_url) 与源码没有变化,但需要提到的是视频中的url是以数字.html结尾,但实际上通过升级,新的URL已经发生了变化,但使用urllib.parse.urljoin()还是能够得到一个正确的URL。
    查看全部
  • python3.6下 import urllib.request import http.cookiejar url = 'https://baidu.com' print('urllib下载网页方法1:最简洁方法') #直接请求 res = urllib.request.urlopen(url) #获取状态码,如果是200则获取成功 print(res.getcode()) #读取内容 #cont是很长的字符串就不输出了 cont = res.read() print('urllib下载网页方法2:添加data、http header') #创建Request对象 request = urllib.request.Request(url) #添加数据 request.data = 'a' #添加http的header #将爬虫伪装成Mozilla浏览器 request.add_header('User-Agent', 'Mozilla/5.0') #发送请求获取结果 response = urllib.request.urlopen(request) print('urllib下载网页方法3:添加特殊情景的处理器') #创建cookie容器 cj = http.cookiejar.CookieJar() #创建一个opener opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) #给urllib安装opener urllib.request.install_opener(opener) #使用带有cookie的urllib访问网页 response = urllib.request.urlopen(url)
    查看全部
  • 调度器相当于是一个命令发布枢纽和中转站,由它来指挥三大模块(URL管理器、下载器、解析器)工作,并最终将价值数据输送给应用端。
    查看全部
  • class UrlManager(object): def __init__(self):#初始化 self.new_urls=set() self.old_urls=set() #向URL管理器中添加一个新的URL def add_new_url(self,url): if url is None: return if url not in self.new_urls and url not in self.old_urls : self.new_urls.add(url) #向URL管理器中批量添加新的URL def add_new_urls(self,urls): if urls is None or len(urls)==0: return for url in urls: self.add_new_url(url)#调用单条添加方法 #判断URL管理器中是否有新的待爬取的URL def has_new_url(self): return len(self.new_urls)!=0 #从URL管理器中获取一个新的带爬取的URL def get_new_url(self): new_url=self.new_urls.pop()#返回一个URL并从中移除这条URL self.old_urls.add(new_url)#添加到 self.old_urls中 return new_url
    查看全部
    3 采集 收起 来源:URL管理器

    2016-06-13

  • # coding:utf-8 from bs4 import BeautifulSoup import re html_doc = "" #引用段落自http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-the-tree,其中的短文,因笔记字数要求有限,无法直接复制过来 soup = BeautifulSoup(html_doc, 'html.parser', from_encoding="utf-8") print u"获取所有的链接" links = soup.find_all('a') for link in links: print link.name, link['href'], link.get_text() print u"获取lacie的链接" link_node = soup.find('a', href="http://example.com/lacie") print link_node.name, link_node['href'], link_node.get_text() print u"正则匹配" link_node = soup.find('a', href=re.compile(r"ill")) print link_node.name, link_node['href'], link_node.get_text() print u"获取p段落文字" p_node = soup.find('p', class_="title") print p_node.name, p_node.get_text()
    查看全部
  • 多种网页解析器
    查看全部
  • ''' Created on 2016年3月29日 @author: leilv ''' import urllib.request import http.cookiejar import urllib.response print('*'*80,'第一种方法') url = "http://www.baidu.com" response1 = urllib.request.urlopen(url) print (response1.getcode()); print (len(response1.read())) #打印网页内容的长度 print('*'*80,'第二种方法') request = urllib.request.Request(url) request.add_header("user-agent", "Mozilla/5.0") response2 = urllib.request.urlopen(request) print(response2.getcode()) print(len(response2.read())) print('*'*80,'第三种方法') cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) urllib.request.install_opener(opener) response3 = urllib.request.urlopen(url) print(cj) print(opener) print(response3.getcode()) print(len(response3.read()))
    查看全部

举报

0/150
提交
取消
课程须知
本课程是Python语言开发的高级课程 1、Python编程语法; 2、HTML语言基础知识; 3、正则表达式基础知识;
老师告诉你能学到什么?
1、爬虫技术的含义和存在价值 2、爬虫技术架构 3、组成爬虫的关键模块:URL管理器、HTML下载器和HTML解析器 4、实战抓取百度百科1000个词条页面数据的抓取策略设定、实战代码编写、爬虫实例运行 5、一套极简的可扩展爬虫代码,修改本代码,你就能抓取任何互联网网页!

微信扫码,参与3人拼团

意见反馈 帮助中心 APP下载
官方微信
友情提示:

您好,此课程属于迁移课程,您已购买该课程,无需重复购买,感谢您对慕课网的支持!