requests和lxml实现爬虫的方法


Posted in Python onJune 11, 2017

如下所示:

# requests模块来请求页面
# lxml模块的html构建selector选择器(格式化响应response)
# from lxml import html
# import requests

# response = requests.get(url).content

# selector = html.formatstring(response)

# hrefs = selector.xpath('/html/body//div[@class='feed-item _j_feed_item']/a/@href')

# 以url = 'https://www.mafengwo.cn/gonglve/ziyouxing/2033.html'为例子

# python 2.7
import requests
from lxml import html
import os
# 获取首页中子页的url链接
def get_page_urls(url):
  response = requests.get(url).content
  # 通过lxml的html来构建选择器
  selector = html.fromstring(response)
  urls = []
  for i in selector.xpath("/html/body//div[@class='feed-item _j_feed_item']/a/@href"):
    urls.append(i)
  return urls
# get title from a child's html(div[@class='title'])
def get_page_a_title(url):
  '''url is ziyouxing's a@href'''
  response = requests.get(url).content
  selector = html.fromstring(response)
  # get xpath by chrome's tool --> /html/body//div[@class='title']/text()
  a_title = selector.xpath("/html/body//div[@class='title']/text()")
  return a_title
# 获取页面选择器(通过lxml的html构建)
def get_selector(url):
  response = requests.get(url).content
  selector = html.fromstring(response)
  return selector
# 通过chrome的开发者工具分析html页面结构后发现,我们需要获取的文本内容主要显示在div[@class='l-topic']和div[@class='p-section']中
# 获取所需的文本内容
 def get_page_content(selector):
   # /html/body/div[2]/div[2]/div[1]/div[@class='l-topic']/p/text()
   page_title = selector.xpath("//div[@class='l-topic']/p/text()")
   # /html/body/div[2]/div[2]/div[1]/div[2]/div[15]/div[@class='p-section']/text()
   page_content = selector.xpath("//div[@class='p-section']/text()")
   return page_title,page_content
# 获取页面中的图片url地址
def get_image_urls(selector):
  imagesrcs = selector.xpath("//img[@class='_j_lazyload']/@src")
  return imagesrcs
# 获取图片的标题

def get_image_title(selector, num)
  # num 是从2开始的
  url = "/html/body/div[2]/div[2]/div[1]/div[2]/div["+num+"]/span[@class='img-an']/text()"
  if selector.xpath(url) is not None:
    image_title = selector.xpath(url)
  else:
    image_title = "map"+str(num) # 没有就起一个
  return image_title
# 下载图片

def downloadimages(selector,number):
  '''number是用来计数的'''
  urls = get_image_urls()
  num = 2
  amount = len(urls)
  for url in urls:
    image_title = get_image_title(selector, num)
    filename = "/home/WorkSpace/tour/words/result"+number+"/+"image_title+".jpg"
    if not os.path.exists(filename):
      os.makedirs(filename)
    print('downloading %s image %s' %(number, image_title))
    with open(filename, 'wb') as f:
      f.write(requests.get(url).content)
    num += 1
  print "已经下载了%s张图" %num
# 入口,启动并把获取的数据存入文件中
if __name__ =='__main__':
  url = 'https://www.mafengwo.cn/gonglve/ziyouxing/2033.html'
  urls = get_page_urls(url)
  # turn to get response from html
  number = 1
  for i in urls:
    selector = get_selector(i)
    # download images
    downloadimages(selector,number)
    # get text and write into a file
    page_title, page_content = get_page_content(selector)
    result = page_title+'\n'+page_content+'\n\n'
    path = "/home/WorkSpace/tour/words/result"+num+"/"
    if not os.path.exists(filename):
      os.makedirs(filename)
    filename = path + "num"+".txt"
    with open(filename,'wb') as f:
      f.write(result)
    print result

到此就结束了该爬虫,爬取页面前一定要认真分析html结构,有些页面是由js生成,该页面比较简单,没涉及到js的处理,日后的随笔中会有相关分享

以上这篇requests和lxml实现爬虫的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用urlparse分析网址中域名的方法
Apr 15 Python
在Python中操作时间之tzset()方法的使用教程
May 22 Python
Python HTTP客户端自定义Cookie实现实例
Apr 28 Python
Python实现读取json文件到excel表
Nov 18 Python
python实现寻找最长回文子序列的方法
Jun 02 Python
python使用minimax算法实现五子棋
Jul 29 Python
解决使用export_graphviz可视化树报错的问题
Aug 09 Python
基于Python的微信机器人开发 微信登录和获取好友列表实现解析
Aug 21 Python
python中的split()函数和os.path.split()函数使用详解
Dec 21 Python
Tensorflow全局设置可见GPU编号操作
Jun 30 Python
Python中生成ndarray实例讲解
Feb 22 Python
用Python可视化新冠疫情数据
Jan 18 Python
Python实现自动登录百度空间的方法
Jun 10 #Python
Python实现获取命令行输出结果的方法
Jun 10 #Python
Python实现查找匹配项作处理后再替换回去的方法
Jun 10 #Python
新手如何快速入门Python(菜鸟必看篇)
Jun 10 #Python
python+requests+unittest API接口测试实例(详解)
Jun 10 #Python
基于python爬虫数据处理(详解)
Jun 10 #Python
python实现稀疏矩阵示例代码
Jun 09 #Python
You might like
Ext.FormPanel 提交和 Ext.Ajax.request 异步提交函数的区别
2009/11/12 Javascript
YUI的Tab切换实现代码
2010/04/11 Javascript
javascript对数组的常用操作代码 数组方法总汇
2011/01/27 Javascript
关于递归运算的顺序测试代码
2011/11/30 Javascript
自己写的兼容ie和ff的在线文本编辑器类似ewebeditor
2012/12/12 Javascript
JS 两个字符串时间的天数差计算
2013/08/25 Javascript
javascript仿php的print_r函数输出json数据
2013/09/13 Javascript
js QQ客服悬浮效果实现代码
2014/12/12 Javascript
使用原生JS实现弹出层特效
2014/12/22 Javascript
jQuery链使用指南
2015/01/20 Javascript
javascript 应用小技巧方法汇总
2015/07/05 Javascript
移动端利用H5实现压缩图片上传功能
2017/03/29 Javascript
JavaScript中附件预览功能实现详解(推荐)
2017/08/15 Javascript
vue中的计算属性实例详解
2018/09/19 Javascript
为nuxt项目写一个面包屑cli工具实现自动生成页面与面包屑配置
2019/09/29 Javascript
Vue 集成 PDF.js 实现 PDF 预览和添加水印的步骤
2021/01/22 Vue.js
python套接字流重定向实例汇总
2016/03/03 Python
Python实现打印螺旋矩阵功能的方法
2017/11/21 Python
怎么使用pipenv管理你的python项目
2018/03/12 Python
Python之列表的插入&替换修改方法
2018/06/28 Python
python爬取盘搜的有效链接实现代码
2019/07/20 Python
python set集合使用方法解析
2019/11/05 Python
使用Python的Turtle库绘制森林的实例
2019/12/18 Python
python实现猜数游戏(保存游戏记录)
2020/06/22 Python
英国第二大营养品供应商:Vitabiotics
2016/10/01 全球购物
韩都衣舍天猫官方旗舰店:天猫女装销售总冠军
2017/10/10 全球购物
ALDO英国官网:加拿大女鞋品牌
2018/02/19 全球购物
全球最大的瓷器、水晶和银器零售商:Replacements
2020/06/15 全球购物
综合办公室个人的自我评价
2013/12/22 职场文书
工程业务员岗位职责
2013/12/31 职场文书
电视购物广告词
2014/03/19 职场文书
清明节网上祭英烈寄语2015
2015/03/04 职场文书
铁人纪念馆观后感
2015/06/16 职场文书
圣诞晚会主持词
2015/07/01 职场文书
html+css实现分层金字塔的实例
2021/06/02 HTML / CSS
python可视化大屏库big_screen示例详解
2021/11/23 Python