Advertisement

python网页爬取方法_Python爬取网页的三种方法

阅读量:

Python爬取网页的一种常用方法:其中一种常见的获取网页参数的方法是采用 urllib 模块中的 getparam 方法;另一种则是利用 urllib2 模块实现同样的功能。

Python爬取网页的一种常用方法:其中一种常见的获取网页参数的方法是采用 urllib 模块中的 getparam 方法;另一种则是利用 urllib2 模块实现同样的功能。

import urllib

fopen1 = urllib.urlopen('http://www.baidu.com').info()

fopen2 = urllib2.urlopen('http://www.sina.com').info()

print fopen1.getparam('charset')

print fopen2.getparam('charset')

#----有些网站有反爬虫技术,需要如下办法----

url = 'http://www.qiushibaike.com/hot/page/1'

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

headers = { 'User-Agent' : user_agent }

request = urllib2.Request(url,headers = headers)

c_res=urllib2.urlopen(request).info()

print c_res.getparam('charset')

Python爬取网页的三种方法之二 : 基于chardet模块实现 ---体验上感觉比第一种方法略显不如快

import chardet

import urllib

#先获取网页内容

data1 = urllib.urlopen('http://www.baidu.com').read()

#用chardet进行内容分析

chardit1 = chardet.detect(data1)

print chardit1['encoding']

#----有些网站有反爬虫技术,需要如下办法----

url = 'http://www.qiushibaike.com/hot/page/1'

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

headers = { 'User-Agent' : user_agent }

response = urllib2.urlopen(request).read()

chardit1 = chardet.detect(response)

print chardit1['encoding']

Python爬取网页的三种方法之三 : 利用BeautifulSoup模块方法

from bs4 import BeautifulSoup

import urllib2

content=urllib2.urlopen('http://www.baidu.com')

soup=BeautifulSoup(content)

print soup.original_encoding #这里的输出就是网页的编码方式

#----有些网站有反爬虫技术,需要与上述两办法类似处理----

全部评论 (0)

还没有任何评论哟~