Skip to main content
  1. Posts/

爬虫学习笔记

·3 mins
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

再次迫于生计。。。

参考了面向新人的 Python 爬虫学习资料

大致的学习路线为:

一: 简单的定向脚本爬虫( request — bs4 — re )

二: 大型框架式爬虫( Scrapy 框架为主)

三:浏览器模拟爬虫 ( Mechanize 模拟 和 Selenium 模拟)

有Python基础和一点html基础的话。。。貌似上手是0难度的

年轻人的第一个爬虫(虽然代码是直接copy的…

  1'''
  2抓取百度贴吧---生活大爆炸吧的基本内容
  3爬虫线路: requests - bs4
  4Python版本: 3.6
  5OS: mac os 12.12.4
  6'''
  7
  8import requests
  9import time
 10from bs4 import BeautifulSoup
 11
 12# 首先我们写好抓取网页的函数
 13
 14
 15def get_html(url):
 16    try:
 17        r = requests.get(url, timeout=30)
 18        r.raise_for_status()
 19        # 这里我们知道百度贴吧的编码是utf-8,所以手动设置的。爬去其他的页面时建议使用:
 20        # r.endcodding = r.apparent_endconding
 21        r.encoding = 'utf-8'
 22        return r.text
 23    except:
 24        return " ERROR "
 25
 26
 27def get_content(url):
 28    '''
 29    分析贴吧的网页文件,整理信息,保存在列表变量中
 30    '''
 31
 32    # 初始化一个列表来保存所有的帖子信息:
 33    comments = []
 34    # 首先,我们把需要爬取信息的网页下载到本地
 35    html = get_html(url)
 36
 37    # 我们来做一锅汤
 38    soup = BeautifulSoup(html, 'lxml')
 39
 40    # 按照之前的分析,我们找到所有具有‘ j_thread_list clearfix’属性的li标签。返回一个列表类型。
 41    liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})
 42
 43    # 通过循环找到每个帖子里的我们需要的信息:
 44    for li in liTags:
 45        # 初始化一个字典来存储文章信息
 46        comment = {}
 47        # 这里使用一个try except 防止爬虫找不到信息从而停止运行
 48        try:
 49            # 开始筛选信息,并保存到字典中
 50            comment['title'] = li.find(
 51                'a', attrs={'class': 'j_th_tit '}).text.strip()
 52            comment['link'] = "http://tieba.baidu.com/" + \
 53                li.find('a', attrs={'class': 'j_th_tit '})['href']
 54            comment['name'] = li.find(
 55                'span', attrs={'class': 'tb_icon_author '}).text.strip()
 56            comment['time'] = li.find(
 57                'span', attrs={'class': 'pull-right is_show_create_time'}).text.strip()
 58            comment['replyNum'] = li.find(
 59                'span', attrs={'class': 'threadlist_rep_num center_text'}).text.strip()
 60            comments.append(comment)
 61        except:
 62            print('出了点小问题')
 63
 64    return comments
 65
 66
 67def Out2File(dict):
 68    '''
 69    将爬取到的文件写入到本地
 70    保存到当前目录的 TTBT.txt文件中。
 71
 72    '''
 73    with open('TBBT.txt', 'a+') as f:
 74        for comment in dict:
 75            f.write('标题: {} \t 链接:{} \t 发帖人:{} \t 发帖时间:{} \t 回复数量: {} \n'.format(
 76                comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']))
 77
 78        print('当前页面爬取完成')
 79
 80
 81def main(base_url, deep):
 82    url_list = []
 83    # 将所有需要爬去的url存入列表
 84    for i in range(0, deep):
 85        url_list.append(base_url + '&pn=' + str(50 * i))
 86    print('所有的网页已经下载到本地! 开始筛选信息。。。。')
 87
 88    #循环写入所有的数据
 89    for url in url_list:
 90        content = get_content(url)
 91        Out2File(content)
 92    print('所有的信息都已经保存完毕!')
 93
 94
 95base_url = 'http://tieba.baidu.com/f?kw=&ie=utf-8'
 96# 设置需要爬取的页码数量
 97deep = 100
 98
 99if __name__ == '__main__':
100    main(base_url, deep)

年轻人的第二个爬虫:https://github.com/111qqz/spider-demo,爬了我家一周的天气情况

爬虫能够work我觉得主要取决于两个因素

一个是,一个网站的网页源码,其实是在我们本地存储的

另一个是,网页的代码是有规律的…

所以初级的爬虫的难度就仅仅在于找规律。。。然后配合chrome 开发者工具的模拟点击功能和 xpath这种文本解析工具… 就可以搞定了。。。

关于反爬虫的处理办法,以及如何提高爬虫的速度,可能才是“爬虫工程师”的核心技能?

参考资料:

BeautifulSoup官方文档,一个将html数据结构化的python库

Scrapy官方文档,一个爬虫框架

Related

使用python计算误差代码

·1 min
import os 1import math 2ave_err=0.0 3max_err=0.0 4max_err_rate=0.0 5length=0 6with open("cpu_result.txt","r") as fp1, open("cuda_ppl_result.txt","r") as fp2: 7 for l1 in fp1: 8 l2 = fp2.readline() 9 l1=l1[:-2] 10 l2=l2[:-2] 11 lst = l1.split(' ') 12 lst2 = l2.split(' ') 13 #print lst 14 lst = [float(x) for x in lst ] 15 length = length + len(lst) 16 lst2 = [float(x) for x in lst2] 17 #print (lst) 18 #print (lst2) 19 20 for index,x in enumerate(lst): 21 y = lst2[index] 22 ave_err = ave_err + abs(x-y) 23 max_err = max(max_err,abs(x-y)) 24 max_err_rate = max(max_err_rate,abs(x-y)/x) 25 26 print("len=",length) 27 print("max_err=",max_err) 28 print("max_err_rate=",max_err_rate*100,"%") 29 print("ave_err=",ave_err/length) 需要提供两个文件,并且两个文件的数据格式相同。