'''

从web抓取数据:

webbrowser:是python自带的,打开浏览器获取指定页面.

requests:从因特网上下载文件和网页.

Beautiful Soup:解析HTML,即网页编写的格式.

selenium:启动并控制一个Web浏览器.selenium能够填写表单,并模拟鼠标在这个浏览器中点击

'''

import webbrowser

webbrowser.open('http://inventwithpython.com/')

'''

利用requests模块从Web下载文件:

requests模块让你很容易从Web下载文件,不必担心一些复杂的问题,

诸如网络错误、连接问题和数据压缩

'''

###################################用requests.get()下载一个网页####################################

import requests

res=requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')

type(res)

res.status_code=requests.codes.ok

'''

检查Response对象的status_code属性,等于requests.codes.ok时表示一切都好

(HTTP协议中"OK"的状态码是200,404状态码表示"没找到")

'''

len(res.text)

print(res.text[:250])

###################################检查下载错误####################################

import requests

res=requests.get('http://inventwithpython.com/page_that_does_not_exist')

res.raise_for_status()     ####下载成功了,就什么也不做;下载出错,就抛出异常

##############################################

import requests

res=requests.get('http://inventwithpython.com/page_that_does_not_exist')

try:

res.raise_for_status()

except Exception as exc:

print('There was a problem:%s'%(exc))

###################################将下载的文件保存到硬盘####################################

import requests

res=requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')

res.raise_for_status()

playFile=open(r'C:\Users\Administrator\Desktop\RomeoAndJuliet.txt','wb')

for chunk in res.iter_content(100000):  ###每次循环迭代的字节数

print len(chunk)

playFile.write(chunk)

playFile.close()

###################################学习HTML的资源####################################

'''

HTML初学者指南:

http://htmldog.com/guides/html/beginner/

http://www.codecademy.com/tracks/web/

https://developer.mozilla.org/en-US/learn/html

'''

######HTML快速复习

<strong>Hello</strong>world!  #####<strong>表明:标签包围的文本将使用粗体

Al''s free <a href="http://inventwithpython.com">Python books</a>

###################################查看网页的HTML源代码####################################

'''

在网页任意位置点击右键:选择View Source或View page source

查看该页的HTML文本

'''

'''

在Windows版的Chrome和IE中,开发者工具已经安装了,可以按下F12,出现;

再次按下F12,可以让开发者工具消失

'''

'''

不要用正则表达式来解析HTML:

尝试用正则表达式来捕捉HTML格式的变化,非常繁琐,容易出错

专门用于解析HTML的模块,诸如Beautiful Soup,将更不容易导致缺陷

http://stackoverflow.com/a/1732454/1893164/

'''

###################################使用开发者工具来寻找HTML元素####################################

'''

http://weather.gov/

邮政编码为94105

通过开发者工具,找到对应代码

'''

###################################从HTML创建一个BeautifulSoup对象####################################

import requests,bs4

res=requests.get('http://forecast.weather.gov/MapClick.php?lat=37.78833550000007&lon=-122.39552170000002#.WXazEmP9c_0')

res.raise_for_status()

noStarchSoup=bs4.BeautifulSoup(res.text)

type(noStarchSoup)

playFile=open(r'C:\Users\Administrator\Desktop\rest.html','wb')

for chunk in res.iter_content(100000):  ###每次循环迭代的字节数

print len(chunk)

playFile.write(chunk)

playFile.close()

###################################用select()方法寻找元素####################################

'''

传递给select()方法的选择器                           将匹配...

soup.select('div')                                           所有名为<div>的元素

soup.select('#author')                                 带有id属性为author的元素

soup.select('.notice')                                   所有使用CSS class属性名为notice的元素

soup.select('div span')                                 所有在<div>元素之内的<span>元素

soup.select('div > span')                    所有直接在<div>元素之内的<span>元素,中间没有其他元素

soup.select('input[name]')                         所有名为<input>,并有一个name属性,其值无所谓的元素

soup.select('input[type="button"]') 所有名为<input>,并有一个type属性,其值为button的元素

'''

<div id="current_conditions-summary" class="pull-left">

<p class="myforecast-current">NA</p>

<p class="myforecast-current-lrg">60°F</p>

<p class="myforecast-current-sm">16°C</p>

</div>

<div id="comic">

<img src="//imgs.xkcd.com/comics/barrel_cropped_(1).jpg" title="Don't we all." alt="Barrel - Part 1" />

</div>

import bs4

exampleFile=open(r'C:\Users\Administrator\Desktop\rest.html')

exampleSoup=bs4.BeautifulSoup(exampleFile.read())

elems=exampleSoup.select('#current_conditions-summary')

type(elems)

len(elems)

type(elems[0])

elems[0].getText()

>>> elems[0].getText()

u'\nNA\n59\xb0F\n15\xb0C\n'

>>> str(elems[0])

'<div class="pull-left" id="current_conditions-summary">\n<p class="myforecast-current">NA</p>\n<p class="myforecast-current-lrg">59\xc2\xb0F</p>\n<p class="myforecast-current-sm">15\xc2\xb0C</p>\n</div>'

>>> >>> elems[0].attrs

{'id': 'current_conditions-summary', 'class': ['pull-left']}

#########################

pElems=exampleSoup.select('p')

>>> pElems[1]

<p>Your local forecast office is</p>

>>> pElems[2]

<p>

Severe thunderstorms will be possible over portions of the upper Midwest and Great Lakes Tuesday, Wednesday, and Thursday. Damaging winds, large hail, and heavy rainfall possible. Over the Desert Southwest and portions of the Rockies, Monsoonal moisture will lead to locally heavy rainfall and the threat for flash flooding into midweek.

<a href="http://www.wpc.ncep.noaa.gov/discussions/hpcdiscussions.php?disc=pmdspd" target="_blank">Read More &gt;</a>

</p>

>>> pElems[1].getText()

u'Your local forecast office is'

###################################通过元素的属性获取数据####################################

import bs4

soup=bs4.BeautifulSoup(open(r'C:\Users\Administrator\Desktop\rest.html'))

spanElem=soup.select('span')[0]

>>> str(spanElem)

'<span class="sr-only">Toggle navigation</span>'

>>> spanElem.get('class')

['sr-only']

>>> spanElem.attrs

{'class': ['sr-only']}

>>> spanElem.get('id')==None

True

###################################用selenium模块控制浏览器####################################

###################################启动selenium控制的浏览器####################################

#####下载:http://getfirefox.com/

from selenium import webdriver

browser=webdriver.Firefox()

type(browser)

browser.get('http://inventwithpython.com')

###################################maplt.py####################################

import webbrowser,sys,pyperclip

if len(sys.argv)>1:

###Get address from command line:

address=' '.join(sys.argv[1:])

else:

address=pyperclip.paste()

webbrowser.open('https://www.google.com/maps/place/'+address)

python自动化之web抓取的更多相关文章

  1. 如何用 Python 实现 Web 抓取?

    [编者按]本文作者为 Blog Bowl 联合创始人 Shaumik Daityari,主要介绍 Web 抓取技术的基本实现原理和方法.文章系国内 ITOM 管理平台 OneAPM 编译呈现,以下为正 ...

  2. python Web抓取(一)[没写完]

    需要的模块: python web抓取通过: webbrowser:是python自带的,打开浏览器获取指定页面 requests:从因特网上下载文件和网页 Beautiful Soup:解析HTML ...

  3. python&amp;php数据抓取、爬虫分析与中介,有网址案例

    近期在做一个网络爬虫程序.后台使用python不定时去抓取数据.前台使用php进行展示 站点是:http://se.dianfenxiang.com

  4. Web UI 自动化单个xpath抓取插件详解

    原文地址http://blog.csdn.net/kaka1121/article/details/51878346 单个控件获取 需求: 右键到某个控件上,就能获取到至多三个可以唯一定位该元素的相对 ...

  5. python 手机App数据抓取实战二抖音用户的抓取

    前言 什么?你问我国庆七天假期干了什么?说出来你可能不信,我爬取了cxk坤坤的抖音粉丝数据,我也不知道我为什么这么无聊. 本文主要记录如何使用appium自动化工具实现抖音App模拟滑动,然后分析数据 ...

  6. 基于python编写的天气抓取程序

    以前一直使用中国天气网的天气预报组件都挺好,可是自从他们升级组件后数据加载变得非常不稳定,因为JS的阻塞常常导致网站打开速度很慢.为了解决这个问题决定现学现用python编写一个抓取程序,每天定时抓取 ...

  7. python爬虫 前程无忧网页抓取

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  8. python的post请求抓取数据

    python通过get方式,post方式发送http请求和接收http响应-urllib urllib2 python通过get方式,post方式发送http请求和接收http响应-- import  ...

  9. Python爬虫之一 PySpider 抓取淘宝MM的个人信息和图片

    ySpider 是一个非常方便并且功能强大的爬虫框架,支持多线程爬取.JS动态解析,提供了可操作界面.出错重试.定时爬取等等的功能,使用非常人性化. 本篇通过做一个PySpider 项目,来理解 Py ...

随机推荐

  1. JavaScript验证时间格式

    1. 短时间,形如 (13:04:06) function isTime(str) { var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/) ...

  2. MVC Redirect 页面跳转不了

    1:如果是AJAX调取后台控制器的方法,那么最后跳转的步骤应该在AJAX的success方法里面执行跳转 若果要在控制器跳转那么 应该是前端页面 进行表单提交 在控制器直接用 redire等跳转方法

  3. loadrunner使用过程中的问题记录

    一.录制时选错应用类型,导致提示“loadrunner sockets proxy auto-starter mercury interactive corp.(2002)” 解决办法:重新选择正确的 ...

  4. FileCopy方法

    复制文件. 语法 FileCopy源,目标 FileCopy 语句语法包含以下命名参数: 部分 说明 source 必需. 指定要复制的文件的名称的字符串表达式. _源_可能包含目录或文件夹,和驱动器 ...

  5. Vue渲染数据理解以及Vue指令

    一.Vue渲染数据原理 原生JS改变页面数据,必须要获取页面节点,也即是进行DOM操作,jQuery之类的框架只是简化DOM操作的写法,实质并没有改变操作页面数据的底层原理,DOM操作影响性能(导致浏 ...

  6. charles抓包https/模拟弱网/设置断点重定向/压测

    charles几个常用功能   1,ios 抓包https网页:(如未配置,会显示unknown) 第一步是:给手机安装SSL证书 手机和电脑在同一wifi下,手机wifi配置http代理,ip是电脑 ...

  7. 关于摄像头PCB图设计经验谈

    摄像头PCB设计,因为客观原因等.容易引起干扰这是个涉及面大的问题.我们抛开其它因素,仅仅就PCB设计环节来说,分享以下几点心得,供参考交流: 1.合理布置电源滤波/退耦电容:一般在原理图中仅画出若干 ...

  8. GlusterFS分布式存储集群-2. 使用

    参考文档: Quick Start Guide:http://gluster.readthedocs.io/en/latest/Quick-Start-Guide/Quickstart/ Instal ...

  9. iOS 静态库 与 demo 联合调试

    在修复bug或者开发静态库需要调试,这个时候需要把工程中的.framework和资源bundle文件都替换为静态库原工程文件 首先需要确保静态库工程文件没有打开,Xcode不允许在两个地方同时打开同一 ...

  10. react + antiDesign开发中遇到的问题记录

    react + antiDesign开发中遇到的问题记录 一:页面中子路由失效: antiDesign的官方实例中,会把路由重复的地方给去重,而且路由匹配模式不是严格模式.所以我们需要在util.js ...