zoukankan      html  css  js  c++  java
  • 个人作业1

    由于作业需要爬取疫情信息,

    所以学习了python爬取数据。

    基础知识:

    网络爬虫是一种高效地信息采集利器,利用它可以快速、准确地采集互联网上的各种数据资源,几乎已经成为大数据时代IT从业者的必修课。简单点说,网络爬虫就是获取网页并提取和保存信息的自动化过程,分为下列三个步骤:获取网页、提取信息、保存数据。

    1.获取网页

    使用requests发送GET请求获取网页的源代码。以获取百度为例:

    import requests
    response = requests.get('https://www.baidu.com')
    print(response.text)

    2.提取信息

    Beautiful Soup是Python的一个HTML或XML解析库,速度快,容错能力强,可以方便、高效地从网页中提取数据。基本用法:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'lxml')
    print(soup.prettify())
    print(soup.title.string)

    Beautiful Soup方法选择器:

    find_all()查询符合条件的所有元素,返回所有匹配元素组成的列表。API如下:

    find_all(name,attrs,recursive,text,**kwargs)

    find()返回第一个匹配的元素。举个例子:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'lxml')
    print(soup.find('div', attrs={'class': 'article-list'}))

    3.保存数据

    使用Txt文档保存,兼容性好。

    使用with as语法。在with控制块结束的时候,文件自动关闭。举个例子:

    with open(file_name, 'a') as file_object:
        file_object.write("I love programming.
    ")
        file_object.write("I love playing basketball.
    ")
  • 相关阅读:
    POJ 2112 Optimal Milking (Floyd+二分+最大流)
    hdu5444 Elven Postman
    hdu5442 Favorite Donut
    hdu5437 Alisha’s Party
    hdu5433 Xiao Ming climbing
    hdu5432 Pyramid Split
    Codeforces Round #316 (Div. 2) C. Replacement
    hdu5396 Expression
    hdu3506 Monkey Party
    hdu3516 Tree Construction
  • 原文地址:https://www.cnblogs.com/lxywsx/p/14907740.html
Copyright © 2011-2022 走看看