想用python模拟浏览器访问web的方法测试些东西,有哪几种方法呢?

一类:单纯的访问web,不解析其js,css等。

1. urllib2

#-*- coding:utf-8 -*
import urllib2 def Furllib2(ip,port,url,timeout):
proxydict = {}
proxydict['http'] = "http://%s:%s"%(ip,port)
print proxydict
proxy_handler = urllib2.ProxyHandler(proxydict)
opener = urllib2.build_opener(proxy_handler)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib2.install_opener(opener)
try:
response = urllib2.urlopen(url,timeout=timeout)
print response.geturl()
print response.getcode()
print response.info()
print response.read()
return True
except:
print 'some errors occored' + '-'*50
return 0 def main():
proxyip = '14.18.16.69'
proxyport = '80'
proxy = 'http://2.181.1.127:80'
url = 'http://www.cnblogs.com/'
timeout = 4
print Furllib2(proxyip,proxyport,url,timeout) if __name__ == "__main__":
main()

2. mechanize(与网站的自动化交互)

http://wwwsearch.sourceforge.net/mechanize/doc.html

def Fmechanize(url):
cookies = mechanize.CookieJar()
opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
try:
r = opener.open(url) # GET
# r = opener.open("http://example.com/", data) # POST
print r.geturl()
print r.info()
return True except:
return 0

二类:模拟浏览器,使用firefox等的浏览器引擎,支持js,css等。

1. selenium 的firefox或者chrome等驱动,但是由于要打开一个浏览器,所以会比较慢(浏览器驱动可以到selenium官网上下载,也可以到firefox插件出搜索)

def Fselenium_firefox(ip,port,url,timeout):
try: profile = webdriver.FirefoxProfile()
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.http',ip)
profile.set_preference('network.proxy.http_port', port)
profile.update_preferences()
driver = webdriver.Firefox(profile,timeout = timeout)
except Exception:
print traceback.print_exc()
return 0
pass
try: driver.get(url)
time.sleep(5)
cookies= driver.get_cookies()
print cookies
# driver.get() driver.quit()
return 1 except Exception:
traceback.print_exc()
# print 'not have Union allianceid'
driver.quit()
return 0

2. selenium :headless test使用selenium+ phantomjs驱动,无需打开浏览器,但是支持js的模拟浏览器动作,也就说说和你手工打开是没有区别的。

http://selenium.googlecode.com/git/docs/api/py/api.html

def Fselenium_phantomjs(ip,port,url,timeout):
try:
proxyip = '%s%s%s%s'%('--proxy=',ip,':',port)
proxyport = '--proxy-type=http'
service_args = []
service_args.append(proxyip)
service_args.append(proxyport)
print service_args driver = webdriver.PhantomJS(service_args = service_args)
   #driver = webdriver.PhantomJS("/root/phantomjs-1.9.7-linux-x86_64/bin/phantomjs",service_args = service_args)制定phantomjs的位置
driver.set_page_load_timeout(timeout)
driver.get(url)
time.sleep(4)
except Exception:
traceback.print_exc() try:
geturl = driver.current_url
print driver.current_url
return True
except Exception:
traceback.print_exc()
geturl = None
return 0

3. qt,网上戗来的代码

http://qt-project.org/wiki/PySide#PySide.QtWebKit.PySide.QtWebKit.QWebView.url

from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork

class cookieJar(QtNetwork.QNetworkCookieJar):
def __init__(self, cookiesKey, parent=None):
super(cookieJar, self).__init__(parent) self.mainWindow = parent
self.cookiesKey = cookiesKey
cookiesValue = self.mainWindow.settings.value(self.cookiesKey) if cookiesValue:
cookiesList = QtNetwork.QNetworkCookie.parseCookies(cookiesValue)
self.setAllCookies(cookiesList) # def setCookiesFromUrl (self, cookieList, url):
# cookiesValue = self.mainWindow.settings.value(self.cookiesKey)
# cookiesArray = cookiesValue if cookiesValue else QtCore.QByteArray() # for cookie in cookieList:
# cookiesArray.append(cookie.toRawForm() + "\n") #self.mainWindow.settings.setValue(self.cookiesKey, cookiesArray) #return super(cookieJar, self).setCookiesFromUrl(cookieList, url)
def deleteCookie(self,cookieList):
cookie = []
self.mainWindow.settings.value(cookie)
class webView(QtWebKit.QWebView):
def __init__(self, cookiesKey, url, parent=None):
super(webView, self).__init__(parent) self.cookieJar = cookieJar(cookiesKey, parent) self.page().networkAccessManager().setCookieJar(self.cookieJar) class myWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent) self.cookiesKey = "cookies" self.centralwidget = QtGui.QWidget(self) self.tabWidget = QtGui.QTabWidget(self.centralwidget)
self.tabWidget.setTabsClosable(True) self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.addWidget(self.tabWidget) self.actionTabAdd = QtGui.QAction(self)
self.actionTabAdd.setText("Add Tab")
self.actionTabAdd.triggered.connect(self.on_actionTabAdd_triggered) self.lineEdit = QtGui.QLineEdit(self)
self.lineEdit.setText("http://www.example.com") self.toolBar = QtGui.QToolBar(self)
self.toolBar.addAction(self.actionTabAdd)
self.toolBar.addWidget(self.lineEdit) self.addToolBar(QtCore.Qt.ToolBarArea(QtCore.Qt.TopToolBarArea), self.toolBar)
self.setCentralWidget(self.tabWidget) self.settings = QtCore.QSettings() @QtCore.pyqtSlot()
def on_actionShowCookies_triggered(self):
webView = self.tabWidget.currentWidget()
listCookies = webView.page().networkAccessManager().cookieJar().allCookies() for cookie in listCookies:
print cookie.toRawForm() @QtCore.pyqtSlot()
def on_actionTabAdd_triggered(self):
url = self.lineEdit.text()
self.addNewTab(url if url else 'about:blank') def addNewTab(self, url):
tabName = u"Tab {0}".format(str(self.tabWidget.count())) tabWidget= webView(self.cookiesKey, url, self)
tabWidget.loadFinished.connect(self.on_tabWidget_loadFinished)
tabWidget.load(QtCore.QUrl(url)) tabIndex = self.tabWidget.addTab(tabWidget, tabName) self.tabWidget.setCurrentIndex(tabIndex) @QtCore.pyqtSlot()
def on_tabWidget_loadFinished(self):
cookies2 = self.settings.value(self.cookiesKey) if __name__ == "__main__":
import sys app = QtGui.QApplication(sys.argv)
app.setApplicationName('myWindow') main = myWindow()
main.resize(666, 333)
main.show() sys.exit(app.exec_())

4. qt-headless

http://qt-project.org/wiki/PySide#PySide.QtWebKit.PySide.QtWebKit.QWebView.url

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import * class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_() def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit() url = 'http://webscraping.com'
r = Render(url)
html = r.frame.toHtml()
print html

5. splinter :打开浏览器,模拟操作,python的

http://splinter.cobrateam.info/docs/tutorial.html

>>> from splinter import Browser
>>> browser = Browser()
>>> url = "http://www.cnblogs.com"
>>> browser.visit(url)

具体用哪个要看你有什么具体的需求了

python 模拟浏览器的更多相关文章

  1. 第14.7节 Python模拟浏览器访问实现http报文体压缩传输

    一. 引言 在<第14.6节 Python模拟浏览器访问网页的实现代码>介绍了使用urllib包的request模块访问网页的方法.但上节特别说明http报文头Accept-Encodin ...

  2. Python模拟浏览器多窗口切换

    # 模拟浏览器多窗口切换 # 代码中引入selenium版本为:3.4.3 # 通过Chrom浏览器访问发起请求 # Chrom版本:59 ,chromdriver:2.3 # 需要对应版本的Chro ...

  3. Python模拟浏览器前进后退操作

    # 模拟浏览器前进后退操作 # 代码中引入selenium版本为:3.4.3 # 通过Chrom浏览器访问发起请求 # Chrom版本:59 ,chromdriver:2.3 # 需要对应版本的Chr ...

  4. python模拟浏览器保存Cookie进行会话

    #! /usr/bin/env python # -*-coding:utf- -*- import urllib import urllib2 import cookielib class NetR ...

  5. 用Python模拟浏览器操作

    两种思绪三种要领: 用pamie.建议不要使用,因为pamie为小我私人开发,里面的bug比力多,并且是直接使用win32com体式格局的,如果ie不警惕修改了,后果很严重.另外,pamie3使用的是 ...

  6. python模拟浏览器爬取数据

    爬虫新手大坑:爬取数据的时候一定要设置header伪装成浏览器!!!! 在爬取某财经网站数据时由于没有设置Header信息,直接被封掉了ip 后来设置了Accept.Connection.User-A ...

  7. python:爬虫1——实战(下载一张图片、用Python模拟浏览器,通过在线的有道词典来对文本翻译)

    一.下载一只猫 import urllib.request response = urllib.request.urlopen("http://cdn.duitang.com/uploads ...

  8. python 模拟浏览器登陆coursera

    import requests import random import string def randomString(length): return ''.join(random.choice(s ...

  9. Python模拟浏览器上传文件脚本(Multipart/form-data格式)

    http协议本身的原始方法不支持multipart/form-data请求,这个请求由原始方法演变而来的. multipart/form-data的基础方法是post,也就是说是由post方法来组合实 ...

随机推荐

  1. [大牛翻译系列]Hadoop(8)MapReduce 性能调优:性能测量(Measuring)

    6.1 测量MapReduce和环境的性能指标 性能调优的基础系统的性能指标和实验数据.依据这些指标和数据,才能找到系统的性能瓶颈.性能指标和实验数据要通过一系列的工具和过程才能得到. 这部分里,将介 ...

  2. php操作mysql数据库的基本类

    代码如下 复制代码 <?php$dbhost='localhost';$dbuser='root';$dbpass='123456';$dbname='products';$connect=my ...

  3. 含有自增序列的表中使用truncate与delete的不同结果

    一个含有自增序列的表,使用delete跟truncate之后会有什么不同结果呢? 大概说一下,使用truncate,表中的记录全部被清除,如果向表中插入数据,那么数据的排序是从1开始的. 如果使用的是 ...

  4. android连接本地tomcat服务器,报timeout

    1.在eclipse环境下连接时,没有任何问题 2.直接将服务端发布到tomcat服务下,报timeout 3.查明原因: 3.1打开IE访问,一切正常,可以获取到数据,说明不是服务端的问题 3.2打 ...

  5. 11、创建不使用XAML的WPF应用程序

    首先新建一个空的项目,然后添加一个类,引用一下程序集: PresentationCore.dll PresentationFramework.dll WindowsBase.dll namespace ...

  6. python之内置类型: 序列, 字典

    序列: 元素之类有序的类型. Python 2.x支持6种内置序列: list, tuple, string, ustring, buffer, xrange (1)序列的定义: list: [] t ...

  7. IIS WMI Provider

    section contains information about the classes that are implemented by the IIS WMI provider in the M ...

  8. zip压缩包密码破解

    有一种破解方法叫做Known plaintext attack.市面上的密码破解软件几乎都带有这个功能.操作方法就是找到加密压缩包中的任意一个文件,用同样的压缩软件同样的压缩方式压缩成一个不加密的包, ...

  9. Eclipse 3.7(代号Indigo) 中文字体太小解决办法(转)

    升级到3.7Eclipse最直观的反映就是,中文怎么那么小啊---- 相当不方便. 其实这是Eclipse的默认字体换了,以前的一直是Courier New,现在修改字体也找不到了,算了不找了. 这次 ...

  10. BOM-字节序标记

    BOM——Byte Order Mark 字节序标记 首先是什么是字节序? 字节序:与二进制数据在机器存放位置相关的! 可分为两类: 1. 小端字节序: 低地址放低位数据. x86系列的计算机就使用这 ...