Python爬虫入门

一、使用正则表达式实现爬虫:

  1. Import requests,re
  2. 获取网页源码:htmlsource=requests.get(url).text
  3. 使用正则表达式匹配网页中的内容:

    Re模块常用的函数

    Re.findall(pattern,string,flags=0) #返回内容为包含匹配结果的列表

    Re.sub(pattern,repal,string,count=0) #是用repal替换匹配成功的内容

    Re.search(pattern,string,flags=0) #根据patternstring中匹配字符串,只返回第一次匹配成功的对象

    Re.split(pattern,string,maxsplit=0) #根据pattern分割字符串

    二、使用xpath实现爬虫:

  4. 导入包:from lxml import etree

    Import requests

    获取网页的内容:htmlSource=requests.get(url).text

  5. 提取网页中的内容:

    Selector=etree.HTML(htmlsource)

    Selector.xpath('提取语句')--->返回结果为list列表

    一般用法:

    //定位根节点

    /往下层寻找

    /text() 提取文本内容

    /@xxxx 提取节点的属性值

    特殊用法:

    Starts-with(@属性名称,属性字符相同的部分)

    String(.)标签套标签

  6. 多线程爬虫

    使用map函数

  7. from multiprocessing.dummy import Pool
  8. Pool=Pool(4) #这里的数字写cpu的核心数目
  9. Pool.map(爬取函数,网址列表)
  10. 编码:
  11. 如果想要在python代码中写中文,需要在python代码的第一行加上#-*-coding:utf9-*-
  12. 如果想要输出含有中文的文件需要写一下3行代码:

    Import sys

    Reload(sys)

    Sys.setdefaultencoding('utf-8')

     

原文地址:https://www.cnblogs.com/lightmao/p/4786976.html