Python网络数据采集1-Beautifulsoup的使用

来自此书: [美]Ryan Mitchell 《Python网络数据采集》,例子是照搬的,觉得跟着敲一遍还是有作用的,所以记录下来。

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/page1.html')
soup = BeautifulSoup(res.text, 'lxml')
print(soup.h1)
<h1>An Interesting Title</h1>

使用urllib访问页面是这样的,read返回的是字节,需要解码为utf-8的文本。像这样a.read().decode('utf-8'),不过在使用bs4解析时候,可以直接传入urllib库返回的响应对象。

import urllib.request

a = urllib.request.urlopen('https://www.pythonscraping.com/pages/page1.html')
soup = BeautifulSoup(a, 'lxml')
print(soup.h1)
<h1>An Interesting Title</h1>

抓取所有CSS class属性为green的span标签,这些是人名。

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/warandpeace.html')
soup = BeautifulSoup(res.text, 'lxml')
green_names = soup.find_all('span', class_='green')
for name in green_names:
    print(name.string)
Anna
Pavlovna Scherer
Empress Marya
Fedorovna
Prince Vasili Kuragin
Anna Pavlovna
St. Petersburg
the prince
Anna Pavlovna
Anna Pavlovna
...

孩子(child)和后代(descendant)是不一样的。孩子标签就是父标签的直接下一代,而后代标签则包括了父标签下面所有的子子孙孙。通俗来说,descendant包括了child。

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/page3.html')
soup = BeautifulSoup(res.text, 'lxml')
gifts = soup.find('table', id='giftList').children
for name in gifts:
    print(name)
<tr><th>
Item Title
</th><th>
Description
</th><th>
Cost
</th><th>
Image
</th></tr>

<tr class="gift" id="gift1"><td>
Vegetable Basket
</td><td>
This vegetable basket is the perfect gift for your health conscious (or overweight) friends!
<span class="excitingNote">Now with super-colorful bell peppers!</span>
</td><td>
$15.00
</td><td>
<img src="../img/gifts/img1.jpg"/>
</td></tr>

<tr class="gift" id="gift2"><td>
Russian Nesting Dolls
</td><td>
Hand-painted by trained monkeys, these exquisite dolls are priceless! And by "priceless," we mean "extremely expensive"! <span class="excitingNote">8 entire dolls per set! Octuple the presents!</span>
</td><td>
$10,000.52
</td><td>
<img src="../img/gifts/img2.jpg"/>
</td></tr>

找到表格后,选取当前结点为tr,并找到这个tr之后的兄弟节点,由于第一个tr为表格标题,这样的写法能提取出所有除开表格标题的正文数据。

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/page3.html')
soup = BeautifulSoup(res.text, 'lxml')
gifts = soup.find('table', id='giftList').tr.next_siblings
for name in gifts:
    print(name)
<tr class="gift" id="gift1"><td>
Vegetable Basket
</td><td>
This vegetable basket is the perfect gift for your health conscious (or overweight) friends!
<span class="excitingNote">Now with super-colorful bell peppers!</span>
</td><td>
$15.00
</td><td>
<img src="../img/gifts/img1.jpg"/>
</td></tr>

<tr class="gift" id="gift2"><td>
Russian Nesting Dolls
</td><td>
Hand-painted by trained monkeys, these exquisite dolls are priceless! And by "priceless," we mean "extremely expensive"! <span class="excitingNote">8 entire dolls per set! Octuple the presents!</span>
</td><td>
$10,000.52
</td><td>
<img src="../img/gifts/img2.jpg"/>
</td></tr>

查找商品的价格,可以根据商品的图片找到其父标签<td>,其上一个兄弟标签就是价格。

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/page3.html')
soup = BeautifulSoup(res.text, 'lxml')
price = soup.find('img', src='../img/gifts/img1.jpg').parent.previous_sibling.string
print(price)
$15.00

采集所有商品图片,为了避免其他图片乱入。使用正则表达式精确搜索。

import re
import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/page3.html')
soup = BeautifulSoup(res.text, 'lxml')
imgs= soup.find_all('img', src=re.compile(r'../img/gifts/img.*.jpg'))
for img in imgs:
    print(img['src'])
../img/gifts/img1.jpg
../img/gifts/img2.jpg
../img/gifts/img3.jpg
../img/gifts/img4.jpg
../img/gifts/img6.jpg

find_all()还可以传入函数,对这个函数有个要求:就是其返回值必须是布尔类型,若是True则保留,若是False则剔除。

import re
import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.pythonscraping.com/pages/page3.html')
soup = BeautifulSoup(res.text, 'lxml')
# lambda tag: tag.name=='img'
tags = soup.find_all(lambda tag: tag.has_attr('src'))
for tag in tags:
    print(tag)
<img src="../img/gifts/logo.jpg" style="float:left;"/>
<img src="../img/gifts/img1.jpg"/>
<img src="../img/gifts/img2.jpg"/>
<img src="../img/gifts/img3.jpg"/>
<img src="../img/gifts/img4.jpg"/>
<img src="../img/gifts/img6.jpg"/>

tag是一个Element对象,has_attr用来判断是否有该属性。tag.name则是获取标签名。在上面的网页中,下面的写法返回的结果一样。

lambda tag: tag.has_attr('src')lambda tag: tag.name=='img'


by @sunhaiyu

2017.7.14

Python网络数据采集1-Beautifulsoup的使用的更多相关文章

  1. [python] 网络数据采集 操作清单 BeautifulSoup、Selenium、Tesseract、CSV等

    Python网络数据采集操作清单 BeautifulSoup.Selenium.Tesseract.CSV等 Python网络数据采集操作清单 BeautifulSoup.Selenium.Tesse ...

  2. 笔记之Python网络数据采集

    笔记之Python网络数据采集 非原创即采集 一念清净, 烈焰成池, 一念觉醒, 方登彼岸 网络数据采集, 无非就是写一个自动化程序向网络服务器请求数据, 再对数据进行解析, 提取需要的信息 通常, ...

  3. Python网络数据采集7-单元测试与Selenium自动化测试

    Python网络数据采集7-单元测试与Selenium自动化测试 单元测试 Python中使用内置库unittest可完成单元测试.只要继承unittest.TestCase类,就可以实现下面的功能. ...

  4. Python网络数据采集3-数据存到CSV以及MySql

    Python网络数据采集3-数据存到CSV以及MySql 先热热身,下载某个页面的所有图片. import requests from bs4 import BeautifulSoup headers ...

  5. Python网络数据采集2-wikipedia

    Python网络数据采集2-wikipedia 随机链接跳转 获取维基百科的词条超链接,并随机跳转.可能侧边栏和低栏会有其他链接.这不是我们想要的,所以定位到正文.正文在id为bodyContent的 ...

  6. Python网络数据采集PDF

    Python网络数据采集(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/16c4GjoAL_uKzdGPjG47S4Q 提取码:febb 复制这段内容后打开百度网盘手 ...

  7. 20190715《Python网络数据采集》第 1 章

    <Python网络数据采集>7月8号-7月10号,这三天将该书精读一遍,脑海中有了一个爬虫大体框架后,对于后续学习将更加有全局感. 此前,曾试验看视频学习,但是一个视频基本2小时,全部拿下 ...

  8. Python网络数据采集PDF高清完整版免费下载|百度云盘

    百度云盘:Python网络数据采集PDF高清完整版免费下载 提取码:1vc5   内容简介 本书采用简洁强大的Python语言,介绍了网络数据采集,并为采集新式网络中的各种数据类型提供了全面的指导.第 ...

  9. 《python 网络数据采集》代码更新

    <python 网络数据采集>这本书中会出现很多这一段代码: 1 from urllib.request import urlopen 2 from bs4 import Beautifu ...

随机推荐

  1. Paxos Made Simple(译)

    The Paxos algorithm, when presented in plain English, is very simple. 我叫Leslie Lamport,我最屌. 1. 简介 用于 ...

  2. 探索Windows命令行系列(3):命令行脚本基础

    1.实用功能 1.1.为脚本添加注释 1.2.控制命令的回显 1.3.使用数学表达式 1.4.向脚本传递参数 2.使用变量 2.1.变量的命名及定义 2.2.调用变量 2.3.变量的作用域 3.结构语 ...

  3. (cljs/run-at (JSVM. :browser) "搭建刚好可用的开发环境!")

    前言  书接上一回,在了解cljs基本语法后并在clojurescript.net的奇特错误提示后,我们必须痛定思痛地搭建一个本地的开发环境,以便后续深入地学习cljs. 现有的构建工具  由于浏览器 ...

  4. Sql行列转换参考

    行列转换:SELECT max(case type when 0 then jine else 0 end) a,max(case type when 1 then jine else 0 end) ...

  5. Solr6.6 Tomcat8部署

    原文:https://github.com/x113773/testall/issues/6 准备工作:[solr-6.6.0](http://www.apache.org/dyn/closer.lu ...

  6. Windows7下pip源配置修改

    以下列举三种方式的pip源配置: 1. 设置环境变量PIP_CONFIG_FILE指向pip.ini源配置文件,pip.ini文件内容如下: [global] index-url = http://m ...

  7. tab切换实现方式1

    tab切换实现方式1: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  8. accp8.0转换教材第2章初识MySQL

    首先安装MySQL: 一.单词部分: ①networking网络②option选择③port端口④firewall防火墙⑤engine引擎 ⑥standard标准⑦character字符⑧collat ...

  9. ps命令学习笔记

    最近在看linux优化大师这本书,第2章祥细讲解了分析系统用的工具,这里把一些内容整理出来,以便加深印像. 当进行系统分析时,ps命令显示有关选择的活跃进程的信息.ps命令提供当前已存在的进程列表,和 ...

  10. 给xcode项目修改名字

    在xcode项目开发中,经常会遇到需要修改项目名字的问题, 但是xcode本身修改项目名字比较麻烦,有时候修改的不完全,有时候修改了项目无法打开,无奈只能建一个新项目.这里提供一种修改xcode项目名 ...