python网络爬虫笔记 python网络爬虫学习笔记(1)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python网络爬虫笔记 python网络爬虫学习笔记(1)

赖权华   2021-03-28 我要评论
想了解python网络爬虫学习笔记(1)的相关内容吗,赖权华在本文为您仔细讲解python网络爬虫笔记的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python网络爬虫,python爬虫,python网络爬虫笔记,下面大家一起来学习吧。


(一)   三种网页抓取方法

1、 正则表达式:

模块使用C语言编写,速度快,但是很脆弱,可能网页更新后就不能用了。

2、Beautiful Soup

模块使用Python编写,速度慢。

安装:

pip install beautifulsoup4

3、 Lxml

模块使用C语言编写,即快速又健壮,通常应该是最好的选择。

(二) Lxml安装

pip install lxml

如果使用lxml的css选择器,还要安装下面的模块

pip install cssselect

(三)  使用lxml示例

import urllib.request as re
import lxml.html
#下载网页并返回HTML
def download(url,user_agent='Socrates',num=2):
  print('下载:'+url)
  #设置用户代理
  headers = {'user_agent':user_agent}
  request = re.Request(url,headers=headers)
  try:
    #下载网页
    html = re.urlopen(request).read()
  except re.URLError as e:
    print('下载失败'+e.reason)
    html=None
    if num>0:
      #遇到5XX错误时,递归调用自身重试下载,最多重复2次
      if hasattr(e,'code') and 500<=e.code<600:
        return download(url,num-1)
  return html
html = download('https://tieba.baidu.com/p/5475267611')
#将HTML解析为统一的格式
tree = lxml.html.fromstring(html)
# img = tree.cssselect('img.BDE_Image')
#通过lxml的xpath获取src属性的值,返回一个列表
img = tree.xpath('//img[@class="BDE_Image"]/@src')
x= 0
#迭代列表img,将图片保存在当前目录下
for i in img:
  re.urlretrieve(i,'%s.jpg'%x)
  x += 1

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们