爬虫学习

143 阅读3分钟

最近在修养生息,顺带学习下爬虫,这里做复习的作用。这个爬虫也非常简单,就是爬下页面的网站链接。

一、爬前准备

用的到有以下函数# pip, urllib,BeautifulSoup,re, format, set

pip

pip是python的包管理器,这里说这个的原因是后边的BeautifulSoup需要安装,这里有菜鸟驿站的传送阵

安装使用也非常简单。前往pip官网

我使用的是另外一种: 获取get-pip.py的文件,直接点击就安装上了。这个是文件地址:bootstrap.pypa.io/get-pip.py

检验

pip --version

image.png

出现以下内容就是安装上了

urllib

urllib 库用于操作网页 URL,并对网页的内容进行抓取处理。 urllib库有四个模块

urllib.request

打开和读取url

语法格式:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, context=None)
  1. url:url地址
  2. data:发送到服务器的其他数据对象,默认为none
  3. timeout:设置访问超时时间
  4. cafile 和 capath:cafile 为 CA 证书, capath 为 CA 证书的路径,使用 HTTPS 需要用到
  5. context:ssl.SSLContext类型,用来指定 SSL 设置。

read()

读取整个网页内容,可以指定长度

from urllib.request import urlopen

myURL = urlopen("https://www.baidu.com")
print(myURL.read())

结果如下

image.png

readline()

读取文件的一行内容

from urllib.request import urlopen

html = urlopen('https://www.baidu.com')
print(html.readline())

image.png

readlines()

读取文件的全部内容,它会把读取的内容赋值给一个列表变量

from urllib.request import urlopen

html = urlopen('https://www.baidu.com')
print(html.readlines())

image.png

getcode()

获取网页状态码

from urllib.request import urlopen

html = urlopen('https://www.baidu.com')
print(html.getcode())

image.png

urllib.error

定义异常类,error包含两个方法,分别是URLError和HTTPError

urllib.parse

用于解析 URL

语法

urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

urlstring 为 字符串的 url 地址,scheme 为协议类型,

allow_fragments 参数为 false,则无法识别片段标识符。相反,它们被解析为路径,参数或查询组件的一部分,并 fragment 在返回值中设置为空字符串。

from urllib.parse import urlparse

yangqq = urlparse('https://www.yangqq.net/')
print(yangqq)

image.png 返回参数分别是:

  • scheme:URL协议
  • netloc:网络位置部分
  • path:分层路径
  • params:最后路径元素的参数
  • query:查询组件
  • fragment:片段识别

urllib.robotparser

用于解析 robots.txt 文件

class urllib.robotparser.RobotFileParser(url='')

Beautiful Soup

是一个可以从HTML或XML文件中提取数据的Python库. 一般用法

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('https://www.yangqq.net')
bs = BeautifulSoup(html.read(), 'html.parser')

nameList = bs.findAll('span', {'class':'green'})
for name in nameList:
  print(name.get_text())

re

re 模块使 Python 语言拥有全部的正则表达式功能

compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换

set

set()  函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

二、思路

首先获取网页路径,解析,然后查找所有的a标签,如果存在链接就把href的参数添加页面的数据里,通过使用set去重。

三、 实施

  1. 先导入所需要的函数和方法,设置我们查到的数据所要存的数组
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

pages = set()
  1. 写我们所需要的递归函数,把页面所有的a标签遍历出来
  • 首先我们定义一个获取link的函数getLinks
  • 拿到页面以后,查找所有的a标签,并匹配http
  • 拿到a标签数组后,匹配是否有href标签,判断当前值是否在pages里,如果在就过滤掉,不在就添加进去。

完整代码如下:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

pages = set()

def getLinks(pageUrl):
  global pages
  html = urlopen("https://www.xxx.net{}".format(pageUrl))
  bs = BeautifulSoup(html, 'html.parser')
    
  for link in bs.find_all('a', href=re.compile('http')):
    if 'href' in link.attrs:
      if link.attrs['href'] not in pages:
        newPage = link.attrs['href']
        pages.add(newPage)
        print(pages)
        getLinks('')

getLinks('')

结果如下

image.png

新手上路,如有不足之处,望指点!!!谢谢