python进行简单爬虫示例

一直觉得“爬虫”这个词很高大尚,然后就想着感受一下,百度了之后。顿时觉得也没那么高深,实现简单一点的爬虫,即便是菜鸟也可以做到。
一个简单的爬虫,两部分组成,下载html和解析html文档。下面示例中实现了一个爬取糗事百科的首页的笑话的网络爬虫,可作大家参考
工作环境:VS code ,python2.7
需要导入基本包:requests、 BeautifulSoup 、bs4

导入包的方法
进入cmd
输入 python -m pip install XXX(包名)即可自行安装

检测:输入python回车
import XXX(包名)如果没有报错,表面安装导入成功。
获取整个页面的内容如下:

# -*- coding=utf-8 -*-
import requests
from bs4 import BeautifulSoup
# 获取html文档
def get_html(url):
    """get the content of the url"""
    response = requests.get(url)
    response.encoding = 'utf-8'
    print (response.text)

url_joke = "https://www.qiushibaike.com"
html = get_html(url_joke)

上面输出的内容,相当于在网页上右击,查看源码
如果只需要输出制定内容,还需要用到 BeautifulSoup包,下面示例是输出笑话

# -*- coding=utf-8 -*-

import requests
from bs4 import BeautifulSoup

# 获取html文档
def get_html(url):
    """get the content of the url"""
    response = requests.get(url)
    response.encoding = 'utf-8'
    return response.text

# 获取笑话
def get_certain_joke(html):
    """get the joke of the html"""
    soup = BeautifulSoup(html, 'lxml')
    joke_content = soup.select('div.content')[0].get_text()
    return joke_content

url_joke = "https://www.qiushibaike.com"
html = get_html(url_joke)
joke_content = get_certain_joke(html)
print joke_content

代码讲解:
joke_content = soup.select(‘div.content’)[0].get_text()
是输出第一笑话。
如果想输出第二个笑话,则代码改成如下:
joke_content = soup.select(‘div.content’)[1].get_text()
如果你需要输出title,只需要改成下面代码:
joke_content = soup.select(‘title’)[0].get_text()
就输出:糗事百科 - 超搞笑的原创糗事笑话分享社区

参考链接为https://blog.csdn.net/fujianjun6/article/details/72979643/

你可能感兴趣的:(python)