zoukankan      html  css  js  c++  java
  • 小练习

    0.可以新建一个用于练习的html文件,在浏览器中打开。

    1.利用requests.get(url)获取网页页面的html文件

    import requests

    newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'

    res = requests.get(newsurl) #返回response对象

    res.encoding='utf-8'

    2.利用BeautifulSoup的HTML解析器,生成结构树

    from bs4 import BeautifulSoup

    soup = BeautifulSoup(res.text,'html.parser')

    import requests
    newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(newsurl)
    res.encoding='utf-8'
    from bs4 import BeautifulSoup
    soup= BeautifulSoup(res.text,'html.parser')
    print(soup)

    3.找出特定标签的html元素

    soup.p #标签名,返回第一个

    soup.head

    soup.p.name #字符串

    soup.p. attrs #字典,标签的所有属性

    soup.p. contents # 列表,所有子标签

    soup.p.text #字符串

    soup.p.string

    soup.select(‘li')

    import requests
    newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(newsurl)
    res.encoding='utf-8'
    from bs4 import BeautifulSoup
    soup= BeautifulSoup(res.text,'html.parser')
    print(soup) // soup.XXXXX  此行注解需删

    4.取得含有特定CSS属性的元素

    soup.select('#p1Node')

    soup.select('.news-list-title')

    5.练习:

    取出h1标签的文本

     soup.h1.text   

    取出a标签的链接

    soup.a.attrs['href']

    取出所有li标签的所有内容

     for i in soup.select('li'):
        i.contents

    取出一条新闻的标题、链接、发布时间、来源


    soup.select('.news-list')[0].a.attrs['href']
    '
    http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0329/9122.html'
    soup.select('.news-list')[0].a.select('.news-list-title')[0].text
    for i in soup.select('.news-list')[0].a.select('.news-list-info')[0].contents:
    i.text
  • 相关阅读:
    刘翔那点事
    网站建站模板
    搞笑!from 饮水思源
    我de虚拟经济学系列第一章 经济危机拼命建桥
    IT民工系列——c#操作Microsoft IE,实现自动登录吧!
    商业智能的发展及其应用
    我de虚拟经济学系列第三章 常见的致富之路
    IT民工系列——c#操作EditGrid,自己做一个在线Excel数据库吧!
    Asp.net下的Singleton模式
    asp.net 控件功能小结
  • 原文地址:https://www.cnblogs.com/lg916843/p/8668851.html
Copyright © 2011-2022 走看看