继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python爬虫入门

忽然笑
关注TA
已关注
手记 304
粉丝 64
获赞 276

python爬虫入门

  每个网站都应该提供API,以结构化的格式共享数据。但现实情况下,虽然有提供,但是通常会限制可以抓取的数据,以及访问这些数据的频率。对于网站开发者而言,维护前端界面比维护后端API接口优先级更高。所以应该学习网络爬虫的相关知识。
  前期准备:
1.检查robots.txt文件,了解限制,减少爬虫被封禁的可能性。
2.检查网站地图(Sitemap文件),帮助定位网站最新的内容。
3.估算网站大小(使用串行还是分布式)
4.识别网站所用技术(builtwith模块)

import builtwith
print(builtwith.parse('http://example.webscraping.com'))
#{'web-servers': ['Nginx'], 'web-frameworks': ['Web2py', 'Twitter Bootstrap'], 'programming-languages': ['Python'], 'javascript-frameworks': ['jQuery', 'Modernizr', 'jQuery UI']}

5.寻找网站所有者,用WHOIS协议查询域名的注册者是谁

import whois
print(whois.whois('appspot.com'))12

{ 
 “domain_name”: [ 
   “APPSPOT.COM”, 
   “appspot.com” 
 ], 
 “registrar”: “MarkMonitor, Inc.”, 
 “whois_server”: “whois.markmonitor.com”, 
 “referral_url”: null, 
 “updated_date”: [ 
   “2018-02-06 10:30:28”, 
   “2018-02-06 02:30:29” 
 ], 
 “creation_date”: [ 
   “2005-03-10 02:27:55”, 
   “2005-03-09 18:27:55” 
 ], 
 “expiration_date”: [ 
   “2019-03-10 01:27:55”, 
   “2019-03-09 00:00:00” 
 ], 
 “name_servers”: [ 
   “NS1.GOOGLE.COM”, 
   “NS2.GOOGLE.COM”, 
   “NS3.GOOGLE.COM”, 
   “NS4.GOOGLE.COM”, 
   “ns3.google.com”, 
   “ns1.google.com”, 
   “ns4.google.com”, 
   “ns2.google.com” 
 ], 
 “status”: [ 
   “clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited“, 
   “clientTransferProhibited https://icann.org/epp#clientTransferProhibited“, 
   “clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited“, 
   “serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited“, 
   “serverTransferProhibited https://icann.org/epp#serverTransferProhibited“, 
   “serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited“, 
   “clientUpdateProhibited (https://www.icann.org/epp#clientUpdateProhibited)”, 
   “clientTransferProhibited (https://www.icann.org/epp#clientTransferProhibited)”, 
   “clientDeleteProhibited (https://www.icann.org/epp#clientDeleteProhibited)”, 
   “serverUpdateProhibited (https://www.icann.org/epp#serverUpdateProhibited)”, 
   “serverTransferProhibited (https://www.icann.org/epp#serverTransferProhibited)”, 
   “serverDeleteProhibited (https://www.icann.org/epp#serverDeleteProhibited)” 
 ], 
 “emails”: [ 
   “abusecomplaints@markmonitor.com”, 
   “whoisrelay@markmonitor.com” 
 ], 
 “dnssec”: “unsigned”, 
 “name”: null, 
 “org”: “Google LLC”, 
 “address”: null, 
 “city”: null, 
 “state”: “CA”, 
 “zipcode”: null, 
 “country”: “US” 
}

 重试下载功能:
 

  import urllib3
#num_retries,限制重试次数   def downlaod(url,num_retries=2):
    print('Downloading:',url)    try:
        html=urllib3.urlopen(url).read()    except urllib3.URLERROR as e:
        print('Download error:',e.reason)
        html=None
        if num_retries>0:            if(hasattr(e,'code') and 500<=e.code<600):                return downlaod(url,num_retries-1)    return html

设置用户代理:

import urllib3#num_retries,限制重试次数def downlaod(url,user_agent='wswp',num_retries=2):
    print('Downloading:',url)
    headers={'User_agent':user_agent}
    request=urllib3.Request(url,headers=headers)    try:
        html=urllib3.urlopen(request).read()    except urllib3.URLError as e:
        print('Download error:',e.reason)
        html=None
        if num_retries>0:            if(hasattr(e,'code') and 500<=e.code<600):                #retry 5XX HTTP errors
                return downlaod(url,user_agent,num_retries-1)    return html

网站地图爬虫
sitemap

# -*- coding: utf-8 -*-import refrom common import downloaddef crawl_sitemap(url):
    # download the sitemap file
    sitemap = download(url)    # extract the sitemap links
    links = re.findall('<loc>(.*?)</loc>', sitemap)    # download each link
    for link in links:
        html = download(link)        # scrape html here
        # ...if __name__ == '__main__':
    crawl_sitemap('http://example.webscraping.com/sitemap.xml')

ID遍历爬虫
URL包含页面别名,对优化搜索引擎有帮助,同时这是网站结构的弱点,一般情况下,Web服务器会忽略这个字符串,只使用ID来匹配数据库中的相关记录。
链接爬虫
爬虫限速(延时)
避免爬虫陷阱(设置深度)
(python2.7)
高级链接爬虫:

import reimport urlparseimport urllib2import timefrom datetime import datetimeimport robotparserimport Queuedef link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, headers=None, user_agent='wswp', proxy=None, num_retries=1):
    """Crawl from the given seed URL following links matched by link_regex
    """
    # the queue of URL's that still need to be crawled
    crawl_queue = Queue.deque([seed_url])    # the URL's that have been seen and at what depth
    seen = {seed_url: 0}    # track how many URL's have been downloaded
    num_urls = 0
    rp = get_robots(seed_url)
    throttle = Throttle(delay)
    headers = headers or {}    if user_agent:
        headers['User-agent'] = user_agent    while crawl_queue:
        url = crawl_queue.pop()        # check url passes robots.txt restrictions
        if rp.can_fetch(user_agent, url):
            throttle.wait(url)
            html = download(url, headers, proxy=proxy, num_retries=num_retries)
            links = []

            depth = seen[url]            if depth != max_depth:                # can still crawl further
                if link_regex:                    # filter for links matching our regular expression
                    links.extend(link for link in get_links(html) if re.match(link_regex, link))                for link in links:
                    link = normalize(seed_url, link)                    # check whether already crawled this link
                    if link not in seen:
                        seen[link] = depth + 1
                        # check link is within same domain
                        if same_domain(seed_url, link):                            # success! add this new link to queue
                            crawl_queue.append(link)                            # check whether have reached downloaded maximum
                            num_urls += 1
                            if num_urls == max_urls:                                break
                        else:                            print
                            'Blocked by robots.txt:', url                    class Throttle:
                        """Throttle downloading by sleeping between requests to same domain
                        """

                        def __init__(self, delay):
                            # amount of delay between downloads for each domain
                            self.delay = delay                            # timestamp of when a domain was last accessed
                            self.domains = {}                        def wait(self, url):
                            domain = urlparse.urlparse(url).netloc
                            last_accessed = self.domains.get(domain)                            if self.delay > 0 and last_accessed is not None:
                                sleep_secs = self.delay - (datetime.now() - last_accessed).seconds                                if sleep_secs > 0:
                                    time.sleep(sleep_secs)
                            self.domains[domain] = datetime.now()                    def download(url, headers, proxy, num_retries, data=None):
                        print
                        'Downloading:', url
                        request = urllib2.Request(url, data, headers)
                        opener = urllib2.build_opener()                        if proxy:
                            proxy_params = {urlparse.urlparse(url).scheme: proxy}
                            opener.add_handler(urllib2.ProxyHandler(proxy_params))                        try:
                            response = opener.open(request)
                            html = response.read()
                            code = response.code                        except urllib2.URLError as e:                            print
                            'Download error:', e.reason
                            html = ''
                            if hasattr(e, 'code'):
                                code = e.code                                if num_retries > 0 and 500 <= code < 600:                                    # retry 5XX HTTP errors
                                    return download(url, headers, proxy, num_retries - 1, data)                            else:
                                code = None
                        return html                    def normalize(seed_url, link):
                        """Normalize this URL by removing hash and adding domain
                        """
                        link, _ = urlparse.urldefrag(link)  # remove hash to avoid duplicates
                        return urlparse.urljoin(seed_url, link) def same_domain(url1, url2):
    """Return True if both URL's belong to same domain
    """
    return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netlocdef get_robots(url):
    """Initialize robots parser for this domain
    """
    rp = robotparser.RobotFileParser()
    rp.set_url(urlparse.urljoin(url, '/robots.txt'))
    rp.read()    return rpdef get_links(html):
    """Return a list of links from html
    """
    # a regular expression to extract all links from the webpage
    webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE)    # list of all links from the webpage
    return webpage_regex.findall(html)if __name__ == '__main__':
    link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, user_agent='BadCrawler')
    link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, max_depth=1,
                 user_agent='GoodCrawler')

原文出处

打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP