使用requests爬取网页的四种解析方式(正则、bs4、Xpath、parsel)

部分内容转载自:https://blog.csdn.net/qiushuidongshi/article/details/81252838

目录


0x00 requests爬取网页

0x01 解析方式一——正则

0x02 解析方式二——bs4

0x03 解析方式三——Xpath

0x04 解析方式四——parsel

#0x00 requests爬取网页


import requests
r = requests.get('https://book.douban.com/')
content = r.text

#0x01 解析方式一——正则

import re
pattern=re.compile('<h4.*?>(.*?)</h4>.*?<p>.*?author">.*?(.*?)</span>.*?year">.*?(.*?)</span>.*?publisher">.*?(.*?)</span>.*?</p>',re.S)
 
results = re.findall(pattern, content)
print(results)
for result in results:
    name,author,time,chuban=result
    name=re.sub("\s",'',name).replace(' ','').strip()
    author=re.sub('\s','',author).strip()
    time=re.sub("\s",'',time).strip()
    chuban=re.sub("\s",'',chuban).strip()
    print(name,author,time,chuban)

#0x02 解析方式二——bs4


from bs4 import BeautifulSoup
 
html = r.content
soup = BeautifulSoup(html,"lxml")                              
print(type(soup))                                                                                                                                                                 
name = soup.findAll(name='h4',class_='title',text=re.compile(".*?"))                                                                                                  
author=soup.findAll(name='span',class_='author',text=re.compile(".*?"))                                                                                          
time=soup.findAll(name='span',class_="year",text=re.compile(".*?"))                                                                                                  
chuban=soup.findAll(name="span",class_="publisher",text=re.compile((".*?")))  

#0x03 解析方式三——Xpath

from lxml import etree
 
html=r.content
tree = etree.HTML(html)
name=tree.xpath("//h4/text()")
author=tree.xpath("//span[@class='author']/text()")
time=tree.xpath("//span[@class='year']/text()")
chuban=tree.xpath("//span[@class='publisher']/text()")
print(name,author,time,chuban)

#0x04 解析方式四——parsel

import requests
import parsel
 
 
response = requests.get(url)
sel = parsel.Selector(response.text)  #注意这里的S要大写
 
# re正则
# print(sel.re('正则匹配格式'))
 
# xpath
# print(sel.xpath('xpath').getall()) #getall获取所有
 
# css选择器
# print(sel.css('css选择器 ::text').extract_first())#获取第一个
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值