zoukankan      html  css  js  c++  java
  • python爬虫之路——初识爬虫三大库,requests,lxml,beautiful.

    三大库:requests,lxml,beautifulSoup.

    Request库作用:请求网站获取网页数据。

    get()的基本使用方法

    #导入库

    import requests

    #向网站发送请求,获取数据。

    res= requests.get(‘http://bj.xiaozhu.com/’)

    #打印返回值,<response [200]>成功,<response [404]>,<response [400]>失败

    print(res)

    #打印返回文本

    print(res.test)

    加入请求头伪装成浏览器

    import request

    #User-Agent

    headers={Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360SE} 

    #将heads导入

    res=requests.get('https://www.baidu.com/?tn=92495750_hao_pg',headers=headers)

    print(res.test)

     post()的基本使用:用于提交表单来爬取需要登录才能获得数据的网页。

    增加健壮性和效率

     Requests库的错误和异常分四种:自己分为两种①未发出Reques②未收到Html

    当发现这些错误或异常进行代码修改重新再来,爬虫重新再来,有些数据又爬一次。效率和质量低。

    import request

    #User-Agent

    headers={Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360SE} 

    #将heads导入

    res=requests.get('https://www.baidu.com/?tn=92495750_hao_pg',headers=headers)

    try:

      print(res.test)

    except ConnectionError:

      print('拒绝连接')

     beautifulSoup()库的作用:①解析requests库请求的网页,把网页源代码解析成soup文档。②初步提取

    ①解析requests库请求的网页,把网页源代码解析成soup文档,得到标准缩进格式的结构输出,为进步处理准备。

    #导入库

    import requests

    from bs4 import BeautifulSoup

    #向网站发送请求,获取数据。

    res= requests.get(‘http://bj.xiaozhu.com/’)

    #利用Beauiful库解析为soup文档。

    soup=BeautifulSoup(res.test,'html.parser')

    print(soup.prettify())

    ②初步提取

    find_all和find()的区别:查询一个或查询所有。使用方法一样,没有具体事例可能用的不多。

     根据标签名提取内容

    soup.find_all('div',"item")

    soup.find_all('div',class='item')

    soup.find_all('div',attrs={"class":"item"})

     selector():根据路径查询数据

    soup.selector( div > div > div.lay.first > div.list_li.30 > a > img)

    div是标签名,list_li.30是属性class的值

    多分支标签中不能使用child要改为type

    li:nth-child(1)需改为li:nth-of-type(1)

     ③get_text()方法:提取标签内容去掉头尾,<i>5456</i>      =>    5456

    import requests

    from bs4 import BeautifulSoup

    #向网站发送请求,获取数据。

    res= requests.get(‘http://bj.xiaozhu.com/’)

    #利用Beauiful库解析为soup文档。

    soup=BeautifulSoup(res.test,'html.parser')

    #利用css定位元素

    prices=soup.selector( div > div > div.lay.first > div.list_li.30 > a > img)

    #提取标签内容去掉头尾,<i>5456</i>=>5456

    for price in prices:

      print (price.get_text())

    lxml库

  • 相关阅读:
    在位图上写字
    删除文件到回收站中
    Blog改名字了
    [C#]强类型
    [C#] 如何选择一个目录
    [.NET]Visual Studio 2003的一个bug
    PHP句法规则详解
    php获取本地实际IP
    从0开始学编程(1)115 大致了解
    httpd2.2.21 + php5.3.8 自动安装脚本
  • 原文地址:https://www.cnblogs.com/lanbofei/p/8675218.html
Copyright © 2011-2022 走看看