'''

从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. vs2012调试时,抛出异常的等待时间很慢,原来是QQ电脑管家搞的鬼。

    vs2012调试时,抛出异常的等待时间以前都正常,不知什么时候起变得很慢,就是出错以后要等30秒以上才会提示,一直找不到原因. 今天看了一下任务管理器,发现有个QQpcrTP进程(好像是,因为卸载了) ...

  2. nGrinder性能测试平台的安装部署

    1.从GitHub下载war包: https://github.com/naver/ngrinder/releases 2.把ngrinder-controller-3.4.2.war重命名为ngri ...

  3. SQL Server Management Studio 键盘快捷键

    光标移动键盘快捷键 操作 SQL Server 2012 SQL Server 2008 R2 左移光标 向左键 向左键 右移光标 向右键 向右键 上移光标 向上键 向上键 下移光标 向下键 向下键 ...

  4. Python的with语句(文件打开方式)

    Python文件打开方式(with语句) python编程中对于文件的打开方式主要有以下两种: 1.利用直接性的open("","")函数:(举例说明) try ...

  5. linux shell 完成批量压缩文件

    首先得到文件列表 使用 list -1 注意是1 不是l 然后是用一个循环内包装zip代码 #!/bin/bash list=`` for var in $list do echo $var zip ...

  6. Unity3D画面渲染官方教程(一)对光照和渲染的介绍

    本系列是对官方教程的翻译加上自己的一些理解译著的,官方网址:https://unity3d.com/cn/learn/tutorials/s/graphics 翻译上尽量保证准确性,但不排除省略或者添 ...

  7. 特效Shader对雾的处理

    RFX4_Particle.shader案例 #ifdef BlendAdd UNITY_APPLY_FOG_COLOR(i.fogCoord, res, half4(0,0,0,0)); #endi ...

  8. Unity中容易被忽略的小技巧

    今天在游戏蛮牛上看到慕容小匹夫的一篇文章,感觉对自己现在的水平很实用,就给转载了过来,以便日后好温习一下. 这里还是要支持原创作者,原文地址在这里 一.编辑器染色 一个常见的工作情景是我们在调整场景内 ...

  9. 通过扩展方法简化UnityAPI调用

    通过扩展方法简化UnityAPI调用 扩展方法unity apiapi简化 通过扩展方法简化UnityAPI调用 能省一秒是一秒,时间就是金钱,没人愿意把时间花在冗长的coding上

  10. 使用CNN做数字识别和人脸识别

    上次写的一层神经网络也都贴这里了. 我有点困,我先睡觉,完了我再修改 这个代码写法不太符合工业代码的规范,仅仅是用来学习的的.还望各位见谅 import sys,ossys.path.append(o ...