xpath,bs4和正则的区别

从一个网站爬取数据时可以用很多种方式,我们常用的是xpath,bs4,正则表达式这三种,现在我们来分析一下他们之间的使用差别。

以爬取糗事百科为例,使用xpath需要先在前面写上from lxml import etree,爬取用户姓名的具体代码如下

url="https://www.qiushibaike.com/hot/page/1"
headers={
   'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
response=requests.get(url,headers=headers).text
print(response)
root=etree.HTML(response)
print(root)
#1.xpath 需要引入from lxml import etree
# 通过url得到源码后,需要对源码进行etree处理
# xpath写法先写//这表示从根节点开始无视层级关系寻找,/表示从父节点寻找,设置寻找的条件要使用[@...]表示
name=root.xpath('//div[@class="author clearfix"]/a/h2/text()')
print(name)

使用bs4爬取需要from bs4 import BeautifulSoup

from bs4 import BeautifulSoup
request=Request(url,headers=headers)
response=urlopen(request)
code=response.read().decode()
soup=BeautifulSoup(code,'lxml')
namelist=soup.select('h2')
for name in namelist:
    print(name.string.strip('\n'),end=',')

使用正则表达式需要引入re

code=requests.get(url,headers=headers).content.decode()
pattern=re.compile(r'<div class="author clearfix">.*?<h2>(.*?)</h2>',re.S)
name=pattern.findall(code)
print(name

这三种方式都经常使用,各位就看情况与爱好使用啦

猜你喜欢

转载自blog.csdn.net/qq_37958990/article/details/81291064
今日推荐