突发!员工跳楼!只拿低保工资!央企设计院集体罢工!

突发!北京某院集体罢工!

淄博向东,惠泊向西:在人民与人民币之间,惠泊停车选择了人民币

【少儿禁】马建《亮出你的舌苔或空空荡荡》

10部适合女性看的唯美情色电影

生成图片,分享到微信朋友圈

自由微信安卓APP发布,立即下载! | 提交文章网址
查看原文

5分钟学会Python爬取整个网站

Editor's Note

周末花5分钟学个爬虫可还行

The following article is from 蚂蚁学Python Author 蚂蚁

本图文配套视频演示


爬取网站的步骤:

  1. 设定爬取目标

    • 目标网站:我自己的博客,疯狂的蚂蚁 http://www.crazyant.net

    • 目标数据:所有博客文章的 - 链接、标题、标签

    2. 分析目标网站

    • 爬取页面

    •   http://www.crazyant.net/page/1 ~ http://www.crazyant.net/page/24

    • 待爬取数据:HTML元素中的h2 class=entry-title下的超链接的标题和链接,标签列表

     3. 批量下载HTML

    • 使用requests库实现下载

    • 官网:https://2.python-requests.org//zh_CN/latest/user/quickstart.html

        4. 实现HTML解析,得到目标数据

    • 使用BeautifulSoup库解析

    • 官网:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

        5. 将结果数据存储

    • 可以使用json.dumps把这个数据序列化存储

    • 也可以将数据存入MySQL

  1. import requests

  2. from bs4 import BeautifulSoup

  3. import pprint

  4. import json

1、下载所有的页面的HTML

  1. def download_all_htmls():

  2. """

  3. 下载所有列表页面的HTML,用于后续的分析

  4. """

  5. htmls = []

  6. for idx in range(24):

  7. url = f"http://www.crazyant.net/page/{idx+1}"

  8. print("craw html:", url)

  9. r = requests.get(url)

  10. if r.status_code != 200:

  11. raise Exception("error")

  12. htmls.append(r.text)

  13. return htmls

  1. # 执行爬取

  2. htmls = download_all_htmls()

  1. craw html: http://www.crazyant.net/page/1

  2. craw html: http://www.crazyant.net/page/2

  3. craw html: http://www.crazyant.net/page/3

  4. craw html: http://www.crazyant.net/page/4

  5. craw html: http://www.crazyant.net/page/5

  6. craw html: http://www.crazyant.net/page/6

  7. -- 省略很多行

  8. craw html: http://www.crazyant.net/page/21

  9. craw html: http://www.crazyant.net/page/22

  10. craw html: http://www.crazyant.net/page/23

  11. craw html: http://www.crazyant.net/page/24

  1. htmls[0]

  1. '<!DOCTYPE html><html lang="zh-CN" class="no-js"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width"><link rel="profile" href="http://gmpg.org/xfn/11"><link rel="pingback" href="http://www.crazyant.net/xmlrpc.php"> <!--[if lt IE 9]> <script src="http://www.crazyant.net/wp-content/themes/twentyfifteen/js/html5.js"></script> <![endif]--> <script>(function(html){html.className = html.className.replace(/\\bno-js\\b/,\'js\')})(document.documentElement);</script> <title>疯狂的蚂蚁 &#8211; 视频公众号:蚂蚁学Python</title><link rel=\'dns-prefetch\' href=\'//cdn.bibblio.org\' /><link rel="alternate" type="application/rss+xml" title="疯狂的蚂蚁 &raquo; Feed" href="http://www.crazyant.net/feed" /><link rel="alternate" type="application/rss+xml" title="疯狂的蚂蚁 &raquo; 评论Feed" href="http://www.crazyant.net/comments/feed" /> <!-- mana

2、解析HTML得到数据

  1. def parse_single_html(html):

  2. """

  3. 解析单个HTML,得到数据

  4. @return list({"link", "title", [label]})

  5. """

  6. soup = BeautifulSoup(html, 'html.parser')

  7. articles = soup.find_all("article")

  8. datas = []

  9. for article in articles:

  10. # 查找超链接

  11. title_node = (

  12. article

  13. .find("h2", class_="entry-title")

  14. .find("a")

  15. )

  16. title = title_node.get_text()

  17. link = title_node["href"]


  18. # 查找标签列表

  19. tag_nodes = (

  20. article

  21. .find("footer", class_="entry-footer")

  22. .find("span", class_="tags-links")

  23. .find_all("a")

  24. )

  25. tags = [tag_node.get_text() for tag_node in tag_nodes]

  26. datas.append(

  27. {"title":title, "link":link, "tags":tags}

  28. )

  29. return datas

  1. pprint.pprint(parse_single_html(htmls[0]))

  1. [{'link': 'http://www.crazyant.net/2469.html',

  2. 'tags': ['java', 'spark'],

  3. 'title': 'Spark使用Java开发遇到的那些类型错误'},

  4. {'link': 'http://www.crazyant.net/2454.html',

  5. 'tags': ['pandas', 'python', 'sklearn', '推荐系统'],

  6. 'title': '推荐系统:实现文章相似推荐的简单实例'},

  7. {'link': 'http://www.crazyant.net/2447.html',

  8. 'tags': ['item2vec', 'java', '推荐系统'],

  9. 'title': 'Spark使用word2vec训练item2vec实现内容相关推荐'},

  10. -- 省略很多行

  1. # 执行所有的HTML页面的解析

  2. all_datas = []

  3. for html in htmls:

  4. all_datas.extend(parse_single_html(html))

  1. all_datas

  1. [{'title': 'Spark使用Java开发遇到的那些类型错误',

  2. 'link': 'http://www.crazyant.net/2469.html',

  3. 'tags': ['java', 'spark']},

  4. {'title': '推荐系统:实现文章相似推荐的简单实例',

  5. 'link': 'http://www.crazyant.net/2454.html',

  6. 'tags': ['pandas', 'python', 'sklearn', '推荐系统']},

  7. -- 省略很多行

  1. len(all_datas)

  1. 239

3、将结果输出存储

  1. with open("all_article_links.json", "w") as fout:

  2. for data in all_datas:

  3. fout.write(json.dumps(data, ensure_ascii=False)+"\n")


输出结果文件:


本文的代码在:

https://github.com/peiss/ant-learn-python/tree/master/2019-09-05%205%E5%88%86%E9%92%9F%E5%AD%A6%E4%BC%9APython%E7%88%AC%E5%8F%96%E6%95%B4%E4%B8%AA%E7%BD%91%E7%AB%99


猜你喜欢

数据分析必知必会,缺失值处理技巧大全!(文末送书)


给大家精心18本Python高清电子书,对比学习效率更高哦 !


据说假设检验是个很难的题



文章有问题?点此查看未经处理的缓存