2

Python伪装浏览器爬虫读取网页内容

 2 years ago
source link: https://www.isaced.com/post-197.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python伪装浏览器爬虫读取网页内容

Python

昨天在OSC上看到有段代码,解析HTML相关的,我突然就想到了Python,用Python实现同样功能应该也不难吧,于是我开始试着用Python读取网页内容,不过过程有点纠结。

声明:以下代码在Python 3.3中编写调试完成!

首先我是这样做的:

import urllib.request
url = "http://www.oschina.net/"
data = urllib.request.urlopen(url).read()
print(data)

结果发现不行,OSC加了保护,不止是OSC,CSDN等等很多网站都这样,这就必须要伪装浏览器正常访问了,类似蜘蛛爬虫一样,那么只有给代码加上一个Header,再试试读取HTML。

Chrome如何查看你的浏览器的Header:

Chrome header

一图全解,有木有。

F12打开开发人员工具,其他浏览器也有类似功能,很方便哦,这里我们只需要Request Headers中的User-Agent就可以了。

各种纠结呀,网上许多代码都是Python2的,我用的3.3,import很多都不一样了,没办法只有翻Python的官方文档,全英文有点苦,还好我的Chrome可以随时翻译,减轻负担呀。

在官方文档3.3中找到了urllib.request的文档:docs.python.org/3/library/urllib.request.html

在Examples中找到了一个addheaders的方法,试了一下果然能行,下面就是代码。

'''
Created on 2013-1-27
@author: isaced
''' 
import urllib.request

url = "http://www.oschina.net/"
headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')

opener = urllib.request.build_opener()
opener.addheaders = [headers]
data = opener.open(url).read()

print(data)

到这里就能输出页面的HTML了,也可以直接保存成本地HTML文件,打开正常。 另外对于这编码问题还是有点迷茫。 另收藏一条很有用的语句,type(),类似于C语言中的typeof(),可以print出来直接查看数据类型,很方便!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK