Python简单实现网页内容抓取功能示例

yipeiwu_com6年前Python爬虫

本文实例讲述了Python简单实现网页内容抓取功能。分享给大家供大家参考,具体如下:

使用模块:

import urllib2 
import urllib

普通抓取实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib2
url = 'http://www.baidu.com'
#创建request对象
request = urllib2.Request(url)
#发送请求,获取结果
try:
 response = urllib2.urlopen(request)
except BaseException, err:
 print err
 exit()
#获取状态码,如果是200表示获取成功
code = response.getcode()
print code
#读取内容
if 200 == code:
 content = response.read() 
 print content

Get请求抓取实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib2
import urllib
#urllib2使用GET方式的请求
url = 'http://www.baidu.com/s'
values = {'wd' : '车云'}
# 必须编码
data = urllib.urlencode(values) 
url = url + '?' + data 
print url
#url == http://www.baidu.com/s?wd=%E8%BD%A6%E4%BA%91
#创建request对象
request = urllib2.Request(url)
#发送请求,获取结果
try:
 response = urllib2.urlopen(request)
except BaseException, err:
 print err
 exit()
#获取状态码,如果是200表示获取成功
code = response.getcode()
print code
#读取内容
if 200 == code:
 content = response.read() 
 print content

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

在Python3中使用asyncio库进行快速数据抓取的教程

web数据抓取是一个经常在python的讨论中出现的主题。有很多方法可以用来进行web数据抓取,然而其中好像并没有一个最好的办法。有一些如scrapy这样十分成熟的框架,更多的则是像me...

Python实现爬虫设置代理IP和伪装成浏览器的方法分享

1.python爬虫浏览器伪装 #导入urllib.request模块 import urllib.request #设置请求头 headers=("User-Agent","Moz...

python实现爬虫统计学校BBS男女比例之多线程爬虫(二)

接着第一篇继续学习。 一、数据分类 正确数据:id、性别、活动时间三者都有 放在这个文件里file1 = 'ruisi\\correct%s-%s.txt' % (startNum, e...

python爬虫 爬取58同城上所有城市的租房信息详解

python爬虫 爬取58同城上所有城市的租房信息详解

代码如下 from fake_useragent import UserAgent from lxml import etree import requests, os import...

Python网络爬虫之爬取微博热搜

Python网络爬虫之爬取微博热搜

微博热搜的爬取较为简单,我只是用了lxml和requests两个库 url= https://s.weibo.com/top/summary?Refer=top_hot&topnav=1...