zoukankan      html  css  js  c++  java
  • python-网络安全编程第五天(爬虫模块BeautifulSoup)

    前言

    昨晚学的有点晚 睡得很晚了,今天早上10点多起来吃完饭看了会电视剧就瞌睡了一直睡到12.50多起来洗漱给我弟去开家长会 开到快4点多才回家。耽搁了不少学习时间,现在就把今天所学的内容总结下吧。

    BeautifulSoup模块介绍

    Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.

    使用方法流程

    1.解析内容
    from bs4 import BeautifulSoup
    soup=beautifulSoup(html_doc)
    2.浏览数据
    soup.title
    soup.title.string
    3.BeautifulSoup正则使用
    soup.find_all(name='x',attrs={'xx':re.compile('xxx')})
    name 代表标签
    attrs 标签内东西

    基本使用
    1.标签选择
    print(soup.title)
    2.获取名称
    soup.title.name
    3.获取内容
    print(soup.p.string)
    4.嵌套选择
    print(soup.head.title.string)

    演示eg:

     1 爬取某度传课课程的名称
     2 import requests
     3 from bs4 import BeautifulSoup
     4 
     5 url="https://chuanke.moudu.com/course/72351163642544128_____.html"
     6 
     7 r=requests.get(url)
     8 soup=BeautifulSoup(r.content,'lxml')#选择lxml解析器
     9 10 title_all=soup.find_all(name='div',attrs={'class':'item-title'}) 11 for title in title_all: 12 print(title.a.string)

     1 爬取某度传课课程的名称(配合正则表达式精确爬虫)
     2 import requests
     3 from bs4 import BeautifulSoup
     4 import re
     5 
     6 url="https://chuanke.moudu.com/course/72351163642544128_____.html"
     7 
     8 r=requests.get(url)
     9 soup=BeautifulSoup(r.content,'lxml') #选择lxml解析器
    10 
    11 title_all=soup.find_all(name='a',attrs={'href':re.compile('//chuanke.moudu.com/d*-d*.html')})
    12 for title in title_all:
    13     print(title.string)

    参考学习

    https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#id13  beautifulsoup中文手册

  • 相关阅读:
    js中的面向对象
    js 定时器
    js中 关于DOM的事件操作
    js 函数
    js流程控制;常用内置对象
    js数据类型基础
    js基础语法
    js初识
    css 选择器;盒模型
    软件系统建模之用例视图
  • 原文地址:https://www.cnblogs.com/xhds/p/12203671.html
Copyright © 2011-2022 走看看