爬虫篇(1)——从爬取练习题开始

前言:
介绍小例子,加深对爬虫的理解,主要用bs4完成

主页面:


image.png

副页面:


image.png
  • 代码实现

  • 1.请求主网页源码
from bs4 import BeautifulSoup
import requests
url = "http://www.runoob.com/python/python-100-examples.html"
#发送请求
content = requests.get(url,params=None).content.decode("utf-8")

  • 2.获得每一个副页面的网址
    找到通往副页面网址的标签的id


    image.png
html = BeautifulSoup(content,"html.parser")
# print(type(html))
#查找每个练习的a标签的href属性
a=html.find(id="content").ul.find_all("a")
#创建一个列表保存url
url_list=[]
for x in a:
    url_list.append("http://www.runoob.com"+x["href"])
  • 3.对每一个副页面的内容就行抓取
    找到对应内容的的标签下面的id


    image.png
datas=[]
for i in range(100):
    dic = {}
    html01 = requests.get(url_list[i]).content.decode("utf-8")
    soup02 = BeautifulSoup(html01, "html.parser")
    dic['title'] = soup02.find(id="content").h1.text
    # 题目
    dic['content01'] = soup02.find(id="content").p.next_sibling.next_sibling.text
    # print(content01)
    # 程序分析
    dic['content02'] = soup02.find(id="content").p.next_sibling.next_sibling.next_sibling.next_sibling.text
    try:
        dic['content03'] = soup02.find(class_="hl-main").text
    except Exception as e:
        dic["content03"] = soup02.find("pre").text
   
  • 4.把内容保存到csv文件中
    with open("100_py.csv","a+",encoding="utf-8") as file:
        file.write(dic['title']+"\n")
        file.write(dic['content01']+"\n")
        file.write(dic['content02']+"\n")
        file.write(dic['content03']+"\n")
        file.write("*"*60+"\n")

结果:
可以看到有四千多行数据


image.png

后记:
bs4中的find方法查找标签太麻烦,还是推荐用xpath

爬虫篇(4)——qq音乐爬取
爬虫篇(3)——招聘信息爬取
爬虫篇(2)——爬取博客内容

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,413评论 25 709
  • Python开发简单爬虫(Python2.X版本,Eclipse工具) 一、爬虫介绍 爬虫调度端:启动、停止爬虫,...
    凛0_0阅读 2,188评论 2 10
  • Python版本管理:pyenv和pyenv-virtualenvScrapy爬虫入门教程一 安装和基本使用Scr...
    inke阅读 35,813评论 7 93
  • python函数 1.函数作用 最大化代码重用和最小化代码冗余 流程的分解 2.函数基本概念 def创建对象并赋值...
    疾风先生阅读 312评论 0 0
  • 文/张智友 钢筋囚笼地里面的一棵树 是倔强的我化身成了树。 我蓦然等着寂寞了 所以我长了一颗果 我跟我的果畅谈了一...
    张智友阅读 389评论 0 2

友情链接更多精彩内容