python访问抓取网页常用命令总结

yipeiwu_com6年前Python爬虫

python访问抓取网页常用命令

简单的抓取网页:

import urllib.request  
url="http://google.cn/" 
response=urllib.request.urlopen(url)  #返回文件对象
page=response.read() 

直接将URL保存为本地文件:

import urllib.request  
url="http://google.cn/" 
response=urllib.request.urlopen(url)  #返回文件对象
page=response.read() 

POST方式:

import urllib.parse 
import urllib.request 
 
url="http://liuxin-blog.appspot.com/messageboard/add" 
 
values={"content":"命令行发出网页请求测试"} 
data=urllib.parse.urlencode(values) 

#创建请求对象 
req=urllib.request.Request(url,data) 
#获得服务器返回的数据 
response=urllib.request.urlopen(req) 
#处理数据 
page=response.read() 

GET方式:

import urllib.parse 
import urllib.request 
 
url="http://www.google.cn/webhp" 
 
values={"rls":"ig"} 
data=urllib.parse.urlencode(values) 
 
theurl=url+"?"+data 
#创建请求对象 
req=urllib.request.Request(theurl) 
#获得服务器返回的数据 
response=urllib.request.urlopen(req) 
#处理数据 
page=response.read() 

有2个常用的方法,geturl(),info()

geturl()的设置是为了辨别是否有服务器端的网址重定向,而info()则包含了一系列的信息。

中文问题的处理,会用到 encode()编码 dencode()解码:

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

使用python BeautifulSoup库抓取58手机维修信息

直接上代码: 复制代码 代码如下:#!/usr/bin/python# -*- coding: utf-8 -*- import urllib import os,datetime,st...

python利用selenium进行浏览器爬虫

python利用selenium进行浏览器爬虫

前言 相信大家刚开始在做爬虫的时候,是不是requests和sound这两个库来使用,这样确实有助于我们学习爬虫的知识点,下面来介绍一个算事较复杂的爬虫案例selenium进形打开浏览器...

Python爬虫中urllib库的进阶学习

Python爬虫中urllib库的进阶学习

urllib的基本用法 urllib库的基本组成 利用最简单的urlopen方法爬取网页html 利用Request方法构建headers模拟浏览器操作 error的异常操作 ur...

零基础写python爬虫之使用urllib2组件抓取网页内容

零基础写python爬虫之使用urllib2组件抓取网页内容

版本号:Python2.7.5,Python3改动较大,各位另寻教程。所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地。 类似于使用程序模拟IE浏览器...

python 爬虫一键爬取 淘宝天猫宝贝页面主图颜色图和详情图的教程

实例如下所示: import requests import re,sys,os import json import threading import pprint class s...