python 爬虫-2:添加用户代理和延时下载

对于同一个域名的网站,要求两次链接下载之间应该存在一定的延时,为此写了一个延时类,保证每次下载都存在延时,不会对服务器造成负担:

class Throttle():

    def __init__(self, delay):
        self.delay = delay
        self.domains = {}

    def wait(self,url):
        domian = 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.datetime.now() - last_accessed).seconds

            if sleep.secs > 0:
                time.sleep(sleep_secs) 
        self.domains[domain] = datetime.datetime.now()

同时,也需要为 python 爬虫程序添加 用户代理:

header = {}
header['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'

具体内容详见:

www.wangs0622.com

你可能感兴趣的:(python-爬虫,python,url,爬虫,User-Agent)