python访问网站
#!/usr/bin/env python
# encoding: utf-8
from functools import wraps
import requests
from lxml import html
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import random first_num = random.randint(55, 62)
third_num = random.randint(0, 3200)
fourth_num = random.randint(0, 140) class FakeChromeUA:
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
] chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num) @classmethod
def get_ua(cls):
return ' '.join(['Mozilla/5.0', random.choice(cls.os_type), 'AppleWebKit/537.36',
'(KHTML, like Gecko)', cls.chrome_version, 'Safari/537.36']
) HEADERS = {
'User-Agent': FakeChromeUA.get_ua(),
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Connection': 'keep-alive'
} URL="https://www.taobao.com/"
MAX_RETRY=3 #最大尝试次数
XPATH="//div[@class='cat-title']" #需要检查的xpath
def request(url):
session=requests.Session()
req=session.get(url,headers=HEADERS)
if req.status_code==requests.codes.ok:
req.encoding=req.apparent_encoding
return req.text
return None def getdriver(url):
co=Options()
prefs = {
'profile.default_content_setting_values': {
'images': 2
}
}
co.add_experimental_option('prefs', prefs)
co.add_argument('lang=zh_CN.UTF-8')
co.add_argument('--headless')
co.add_argument('--nogpu')
driver=webdriver.Chrome(chrome_options=co)
driver.get(url)
time.sleep(3)
source=driver.page_source
time.sleep(3)
print("关闭chrome浏览器")
driver.close()
return source
def newdecorator(url,retry,check_xpath):
def decorator(func):
@wraps(func)
def log(*args,**kwargs):
global retry
retry=1
try:
while retry<3:
source=request(url)
if source:
print("开启requests模块")
print("=" * 50)
root=html.fromstring(source)
nodelist=root.xpath(check_xpath)
if nodelist:
return func(source)
else:
print("该网站为ajax生成的网页,开始启用chrome模式")
try:
source=getdriver(url)
except:
print("获取内容失败,再次启动谷歌浏览器")
source = getdriver(url)
break
else:
retry+=1
return func(source)
except Exception as e:
print(e.args)
return log
return decorator @newdecorator(url=URL,retry=MAX_RETRY,check_xpath=XPATH)
def getitem(source):
root=html.fromstring(source)
nodes=root.xpath(XPATH)
print("="*50)
print("开始解析网页")
print("=" * 50)
print("获取商品分类")
for item in nodes:
name=item.xpath(".//text()")
print(name[1])
if __name__ == '__main__':
getitem()
python访问网站的更多相关文章
- python 携带cookie访问网站(python接口测试post)
最近在使用自己研究性能测试工具的时候想到,使用python向服务器不断发送数据以作为并发测试.大概情况如下: #coding=utf-8 import urllib2 import urllib im ...
- Python监控网站运行状况
利用python便捷的类库,可以方便快速实现对网站运行状况的监控,主要包括对80端口(即网站运行端口),其它tcp服务等端口的监控就可以了解服务器大概的一个运行状况,使用的库主要为urllib2及so ...
- 通过cookies跳过验证码登陆页面,直接访问网站的其它URL
我每次手动访问去NN网的一家酒店,就不需要登陆,一旦我用脚本打开就会让我登陆,而登陆页面又有验证码,不想识别验证码,所以就想:“通过cookies跳过验证码登陆页面,直接访问网站的其它URL” 转 ...
- Python Jupyter 网站编辑器
Python Jupyter 网站编辑器 jupyter 是 python的网站编辑器可以直接在网页内编写python代码并执行,内置是通过ipython来调用的.很方便灵活. 安装 1.安装ipyt ...
- Windows Server 2008 R2 下配置证书服务器和HTTPS方式访问网站
http://www.cnblogs.com/zhongweiv/archive/2013/01/07/https.html 配置环境 了解HTTPS 配置CA证书服务器 新建示例网站并发布在IIS ...
- 配置Java SSL 访问网站证书
最近在开发 Java 访问 Azure ServiceBus 时遇到SSL证书问题,导致JAVA报错,不能正常访问,报错信息如下: javax.net.ssl.SSLException: Connec ...
- htaccess文件还可以被用来把访问网站的流量劫持到黑客的网站
看是否有文件上传操作(POST方法), IPREMOVED--[01/Mar/2013:06:16:48-0600]"POST/uploads/monthly_10_2012/view.ph ...
- iptables的conntrack表满了导致访问网站很慢
iptables的conntrack表满了导致访问网站很慢 转载自:https://my.oschina.net/jean/blog/189935 检查系统conntrack表是否满 现象:突然发现访 ...
- js判断是手机还是电脑访问网站
js判断是手机还是电脑访问网站 <script type="text/javascript"> <!- ...
随机推荐
- LightGBM的算法介绍
LightGBM算法的特别之处 自从微软推出了LightGBM,其在工业界表现的越来越好,很多比赛的Top选手也掏出LightGBM上分.所以,本文介绍下LightGBM的特别之处. LightGBM ...
- VS2013 启用avalon 智能提示 Intelligence
第一步: 关闭VS2013. 第二步: 进入目录: C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Packages\schem ...
- BZOJ 4408 FJOI2016 神秘数 可持久化线段树
Description 一个可重复数字集合S的神秘数定义为最小的不能被S的子集的和表示的正整数.例如S={1,1,1,4,13},1 = 12 = 1+13 = 1+1+14 = 45 = 4+16 ...
- 支持ie的时间控件 html
连接:http://www.my97.net/demo/resource/2.4.asp#m248 下载测试:链接: https://pan.baidu.com/s/17AdRa2OTLPI7ndiA ...
- java script 学习
用JavaScript输出文本 <p>我的第一个段落.</p> <script> document.write(Date()); </script> & ...
- incorrect integer value for column 问题解决
最近在用zend框架,然后装了一个项目,发现注册的时候出现 General error: 1366 Incorrect integer value: '' for column 'user_id' a ...
- DataView RowFilter Syntax [C#]
RowFilter语法 private void btnEnquiry_Click(object sender, EventArgs e) { string filterExpression = st ...
- 如何在自家厨房里制作LSD
如何在自家厨房里制作LSD -------------------------------------------------------------------------------- D-麦角酸 ...
- webpack 3.8 使用 extract-text-webpack-plugin 3.0 抽取css失败:You may need an appropriate loader to handle this file type.
webpack 3.8.1 使用 extract-text-webpack-plugin 3.0.2 抽取css时失败,报错: ERROR in ./src/static/style/localTim ...
- How to turn off the binary log for mysqld_multi instances?
Q: MySQL supports running multiple mysqld on the same server. One of the ways is to use mysqld_multi ...