zoukankan      html  css  js  c++  java
  • 网络爬虫基础练习

    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')

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

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

    soup.head

    soup.p.name #字符串

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

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

    soup.p.text #字符串

    soup.p.string

    soup.select(‘li')

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

    soup.select('#p1Node')

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

    5.练习:

    取出h1标签的文本
    取出a标签的链接
    取出所有li标签的所有内容
    取出一条新闻的标题、链接、发布时间、来源

    import requests
    from bs4 import BeautifulSoup as bs
    
    url = "http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0329/9122.html"
    res = requests.get(url).content.decode('utf-8')
    soup = bs(res, 'html.parser')
    h1 = soup.select('h1')[0].get_text()
    print(h1)
    
    a = soup.select('a')
    for href in a:
    print(href.get('href'))
    
    li = soup.select('li')
    for l in li:
    print(l.get_text())
    
    title = soup.select('title')
    print(title)
    
    url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(url).content.decode('utf-8')
    soup = bs(res, 'html.parser')
    h = soup.select('.news-list li a')
    for i in h:
    print(i[0].get('href'))
    print(i[1].get_text())
    

      

  • 相关阅读:
    Java集合学习(8):LinkedList
    Java集合学习(7):ArrayList
    Java集合学习(6):LinkedHashSet
    数据结构与算法19—排序
    ZooKeeper基本介绍
    Java集合学习(5):LinkedHashMap
    Java集合学习(4):HashTable
    Java集合学习(3):HashSet
    java集合学习(2):Map和HashMap
    HTML DOM的创建,删除及替换
  • 原文地址:https://www.cnblogs.com/xung/p/8672590.html
Copyright © 2011-2022 走看看