爬虫基础——正则爬虫、Beautifulsoup爬虫、Lxml爬虫对比

 一、正则爬虫

1.一些基础:

(1)(.*?)

其中“()”表示括号的内容作为返回结果,“.*?”是非贪心算法,匹配任意字符

(2)re模块

re模块使Python拥有全部正则表达式功能,若想通过正则爬虫,首先就需要导入这个模块:

import re

这里介绍利用re模块正则爬虫常用的一个函数:findall(),其语法规则是findall(正则表达式,字符串)。findall()函数能匹配所有符合规律的内容,并以列表的形式返回结果。

(3)补充知识点

re.S 使匹配包括换行符在内的所有字符,跨行匹配。

import re

a='''<div>指数
</div>'''
word=re.findall('<div>(.*?)</div>,a,re.S') #re.S用于跨行匹配
print(word)
#result ['指数'\n]

print(word[0].strip())
#result 指数

二、BeautifulSoup库

beautifulsoup可以很轻松的解析requests请求的网页,并把网页源代码解析为soup文档,便于提取数据。

import requests
from bs4 import  BeautifulSoup

headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
         }  #加入请求头

res=requests.get('http:bj.xiaozhu.com/',headers=headers)
soup=BeautifulSoup(res.text,'lxml') #lxml为beautifulsoup库的解析器
prices=soup.select('#page_list>ul>li>div.result_btm_con.lodgeunitname>span.result_price>i') #此处prices为列表,需循环遍历
for price in prices:
    print(price)

需要注意的结果:soup.select()提取出来的数据仍是以列表的形式存储信息的,为了方便我们后续仍需遍历此列表提取信息。#Copy Selector

比如.csv文件格式列元素依次储存匹配,.xls文件创建工作簿、工作表后写入表头、再按元素位置编写for循环写入元素都需要注意我们获取的数据存储形式和后续写入数据的步骤。

补充:

(1).csv文件存储数据

import csv

fp=open('D:/python/pycharm/爬虫/豆瓣图书.csv','wt',newline='',encoding='utf-8') #创建csv
writer=csv.writer(fp)
writer.writerow(('name','url','author','publisher','date','price','rate','comment')) #写入表头

'''------代码略------'''

writer.writerow((name, url, author, publisher, date, price, rate, comment)) #写入获取的数据内容至csv文件中

fp.close()

(2).xls文件存储数据

import xlwt

header=['title','author','style','complete','introduce','word']

book=xlwt.Workbook(encoding='utf-8') #创建工作簿
sheet=book.add_sheet('Sheet1') #创建工资表
for h in range(len(header)):
    sheet.write(0,h,header[h]) #写入表头
i=1
for list in all_info_list:
    j=0
    for data in list:
        sheet.write(i,j,data)
        j+=1
    i+=1

book.save('起点小说.xls')

三、Lxml爬虫

lxml爬虫涉及到Xpath语法,后续在提取文字信息使需要用到这种规则,此处就不赘述了。#Copy Xpath

import requests
from lxml import etree
res = requests.get(url, headers=headers)
selector=etree.HTML(res.text)
url_infos=selector.xpath('//div[@class="article block untagged mb15"]') #先抓大后抓小,寻找循环点
for url_info in url_infos: #遍历大循环,再通过小路径获取精确数据
    id = url_info.xpath('div[1]/a[2]/h2/text()')[0]
    content = url_info.xpath('a[1]/div/span/text()')[0]
    laugh = url_info.xpath('div[2]/span[1]/i/text()')[0]
    comment = url_info.xpath('div[2]/span[2]/a/i/text()')[0]
    info = {
        'id': id,
        'content': content,
        'laugh': laugh,
        'comment': comment
    } #以字典形式存储获取的数据

四、三种方法对比总结

1.调用的库的区别

import requests
import re    #正则爬虫

import requests
from bs4 import BeautifulSoup #BeautifulSoup爬虫

import requests
form lxml import etree    #Lxml爬虫

2.获取数据路径方式的区别

正则表达式、BeautifulSoup(#Copy Selector)、Lxml(Xpath路径 #Copy Xpath)

3.爬虫速度的区别

requests库用于请求网页获取网页数据,运用正则表达式不需要用BeautifulSoup解析网页数据,可以直接用Python的re模块匹配正则表达式。

正则>Lxml>BeautifulSoup

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值