十分钟能学会的简单python爬虫

简单爬虫三步走,So easy~

本文介绍一个使用python实现爬虫的超简单方法,精通爬虫挺难,但学会实现一个能满足简单需求的爬虫,只需10分钟,往下读吧~

该方法不能用于带有反爬机制的页面,但对于我这样的非专业爬虫使用者,几乎遇到的各种简单爬虫需求都是可以搞定的。

归纳起来,只有简单的3步

  • 使用开发人员工具分析网页HTML
  • 请求网页
  • 获取相应信息

我们以一个简单的需求为例:
wiki百科标普500指数页面中,利用爬虫自动获取 S&P 500指数所对应的所有股票。如图所示:
SP500


第一步:使用开发人员工具分析网页HTML

首先我们要对待爬取的网页人工的进行结构分析
这里我使用的是Google浏览器
进入页面后,按下F12,打开开发人员工具
这里写图片描述
选择开发人员工具左上角的小箭头
这是一个映射工具
通过它你可以轻松的观察网页中每一个渲染后的元素所对应于网页HTML中的位置
这能够帮我们很轻松的完成html的结构分析,从而快速实现一个爬虫
就像这样
table
通过观察,我们发现,所有待爬取的股票信息都位于一个表格中
这个表格对应于一个<table class="wikitable sortable jquery-tablesorter"> 标签
这里写图片描述
而表格中每一行的的股票信息又对应了table 下的一个tr 标签
因此我们爬虫的工作就是get到table 下的所有tr 标签,并解析出相应内容
第一步网页HTML分析,完成!


第二步:请求网页

下面开始进入代码阶段
这里我使用的是Python3
需要用到requestsBeautifulSoup 这两个库
因此别忘记引用:

import bs4
import requests

首先我们需要请求网页:

response = requests.get("http://en.wikipedia.org/wiki/List_of_S%26P_500_companies")

随后使用BeautifulSoup解析

soup = bs4.BeautifulSoup(response.text,"html5lib")

没有错,就是这么简单~


第三步:获取相应信息

结合第一步的分析
我们爬虫的工作就是get到table 下的所有tr 标签,并解析出相应内容
通过BeautifulSoup库的一个核心的方法select 我们便能完成这个工作
首先获取所有的tr 标签

symbolslist = soup.select('table')[0].select('tr')[1:]

然后获取tr 标签中所需的属性并打印出来

symbols = []
for i, symbol in enumerate(symbolslist):
    tds = symbol.select('td')
    symbols.append(
        (
            tds[0].select('a')[0].text,  # Ticker
            tds[1].select('a')[0].text,  # Name
            tds[3].text,                 # Sector
        )
    )

大功告成,最终的程序运行结果如下:
stock

全部代码如下:

import bs4
import requests

if __name__ == "__main__":
    """
        Download and parse the Wikipedia list of S&P500 
        constituents using requests and BeautifulSoup.

        Returns a list of tuples for to add to MySQL.
    """

    # Use requests and BeautifulSoup to download the
    # list of S&P500 companies and obtain the symbol table
    response = requests.get(
        "http://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
    )
    soup = bs4.BeautifulSoup(response.text,"html5lib")

    # This selects the first table, using CSS Selector syntax
    # and then ignores the header row ([1:])
    symbolslist = soup.select('table')[0].select('tr')[1:]

    # Obtain the symbol information for each
    # row in the S&P500 constituent table
    symbols = []
    for i, symbol in enumerate(symbolslist):
        tds = symbol.select('td')
        symbols.append(
            (
                tds[0].select('a')[0].text,  # Ticker
                tds[1].select('a')[0].text,  # Name
                tds[3].text,                 # Sector
            )
        )

    # show the symbols
    showNum =10
    for i in range(showNum):
        print(symbols[i])

猜你喜欢

转载自blog.csdn.net/u011583927/article/details/80789467