python+selenium 爬取中国工业园网
import math
import re import requests from lxml import etree type = "https://www.cnrepark.com/gyy/park{}/"
urlList = []
for i in range(1,8):
url = type.format(i)
urlList.append(url) from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
br = webdriver.Chrome(chrome_options=options) class ChanyeList(object): User_Agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
Refer = "https://www.cnrepark.com" # 初始化
def __init__(self,br):
self.br = br # 使用selenium下载内容
def selenium_download(self,url):
br.get(url)
content = self.br.page_source
return content def get_total_numbers(self,url):
content = self.selenium_download(url)
html = etree.HTML(content)
totalNumbersTxt = html.xpath('.//div[@class="nw_num"]/text()')
import re
totalNumbers = re.findall(r'\d+',totalNumbersTxt[0])
return totalNumbers[0]
# 解析出列表
def html_parse_list(self,content):
html = etree.HTML(content)
listObj = html.xpath('.//div[@class="area"]//div[@class="con_lst"]')
list = []
for item in listObj:
src = item.xpath('./div/a/img/@src')
href = item.xpath('./div//h2/a/@href')
title = item.xpath('./div//h2/a/text()')
list.append({'title':title[0],'href':href[0],"src":src[0]})
return list def optimizeContent(self,res):
res = res.replace('b\'', '')
res = res.replace('\\n', '')
res = res.replace('\'', '')
return res # 解析出详情
def html_parse_detail(self,content):
html = etree.HTML(content)
detail = html.xpath('.//div[@class="right_nr"]/div[1]//div[@class="kfq_box"]/ul')
detail = etree.tostring(detail[0])
detail = self.optimizeContent(str(detail)) # 区域优势
regionalAdvantages = html.xpath('.//div[@id="tbc_81"]')
regionalAdvantages = etree.tostring(regionalAdvantages[0])
regionalAdvantages = self.optimizeContent(str(regionalAdvantages)) # 基础配套
basicConfiguration = html.xpath('.//div[@id="tbc_82"]')
basicConfiguration = etree.tostring(basicConfiguration[0])
basicConfiguration = self.optimizeContent(str(basicConfiguration)) # 优惠政策
preferentialPolicy = html.xpath('.//div[@id="tbc_83"]')
preferentialPolicy = etree.tostring(preferentialPolicy[0])
preferentialPolicy = self.optimizeContent(str(preferentialPolicy)) # 规划建设
planningInformation = html.xpath('.//div[@id="tbc_84"]')
planningInformation = etree.tostring(planningInformation[0])
planningInformation = self.optimizeContent(str(planningInformation)) res = {'detail': detail,
"regionalAdvantages": regionalAdvantages,
"basicConfiguration": basicConfiguration,
"preferentialPolicy": preferentialPolicy,
"planningInformation": planningInformation,
} return res; def crawl_url(self,url):
print("crawl page {}".format(url))
listContent = self.selenium_download(url)
list = self.html_parse_list(listContent)
return list def get_name(self,index):
nameList = [
"特色园区",
"创意园",
"孵化基地",
"商务园区",
"生态园区",
"综合乐园",
"产业园转移区"
]
return nameList[index] # 保存list 获取到详情 保存为html
def save_list(self,list,type_index):
try:
for item in list:
url = item['href']
print("crawl url :"+url)
content = self.selenium_download(url)
detailList = self.html_parse_detail(content)
item['title'] = self.validateTitle(item['title'])
type_name = self.get_name(type_index)
with open("./txt/"+type_name+"-"+item['title']+".html","w") as f:
f.write("<h2>{}</h2>".format(item['title']))
f.write("<div> <a href='{}'><img style='height:80px;height:80px;' src={} /></a></div>".format(item['href'],item['src']))
f.write("<p>{}</p>".format(detailList['detail']))
f.write("<p>{}</p><h3>区位优势:</h3>{}".format(detailList['detail'],detailList['regionalAdvantages']))
f.write("<p>{}</p><h3>基础配套:</h3>{}".format(detailList['detail'],detailList['basicConfiguration']))
f.write("<p>{}</p><h3>优惠政策:</h3>{}".format(detailList['detail'],detailList['preferentialPolicy']))
f.write("<p>{}</p><h3>规划建设:</h3>{}".format(detailList['detail'],detailList['planningInformation']))
f.write("<br>")
f.close()
except Exception as e:
print("Exception:"+str(e))
def validateTitle(self,title):
rstr = r"[\/\\\:\*\?\"\<\>\|\(\)]" # '/ \ : * ? " < > |'
new_title = re.sub(rstr, "_", title) # 替换为下划线
return new_title
if __name__ == "__main__":
try: rootUrl = "https://www.cnrepark.com/gyy/park{}/" for k in range(1,8):
chanyeList = ChanyeList(br)
baseUrl = "https://www.cnrepark.com/gyy/park"+str(k)+"/?publishtime=desc&page={}"
pageUrl = "https://www.cnrepark.com/gyy/park"+str(k)+"/"
# 获取总页数
totalNumbers = chanyeList.get_total_numbers(pageUrl)
totalPage = math.ceil( int(totalNumbers) / 13)
result = []
for page in range(1,int(totalPage) + 1 ):
realUrl = baseUrl.format(page)
list = chanyeList.crawl_url(realUrl)
result.extend(list)
chanyeList.save_list(result,k-1) br.quit()
except Exception as e:
print(str(e))
python+selenium 爬取中国工业园网的更多相关文章
- Python爬取中国天气网
Python爬取中国天气网 基于requests库制作的爬虫. 使用方法:打开终端输入 “python3 weather.py 北京(或你所在的城市)" 程序正常运行需要在同文件夹下加入一个 ...
- 初识python 之 爬虫:爬取中国天气网数据
用到模块: 获取网页并解析:import requests,html5lib from bs4 import BeautifulSoup 使用pyecharts的Bar可视化工具"绘制图表& ...
- Python+Selenium爬取动态加载页面(1)
注: 最近有一小任务,需要收集水质和水雨信息,找了两个网站:国家地表水水质自动监测实时数据发布系统和全国水雨情网.由于这两个网站的数据都是动态加载出来的,所以我用了Selenium来完成我的数据获取. ...
- selenium爬取煎蛋网
selenium爬取煎蛋网 直接上代码 from selenium import webdriver from selenium.webdriver.support.ui import WebDriv ...
- Python+Selenium爬取动态加载页面(2)
注: 上一篇<Python+Selenium爬取动态加载页面(1)>讲了基本地如何获取动态页面的数据,这里再讲一个稍微复杂一点的数据获取全国水雨情网.数据的获取过程跟人手动获取过程类似,所 ...
- Python Scrapy 爬取煎蛋网妹子图实例(一)
前面介绍了爬虫框架的一个实例,那个比较简单,这里在介绍一个实例 爬取 煎蛋网 妹子图,遗憾的是 上周煎蛋网还有妹子图了,但是这周妹子图变成了 随手拍, 不过没关系,我们爬图的目的是为了加强实战应用,管 ...
- Python爬取中国票房网所有电影片名和演员名字,爬取齐鲁网大陆所有电视剧名称
爬取CBO中国票房网所有电影片名和演员名字 # -*- coding: utf-8 -*- # 爬取CBO中国票房网所有电影片名 import json import requests import ...
- python爬取中国知网部分论文信息
爬取指定主题的论文,并以相关度排序. #!/usr/bin/python3 # -*- coding: utf-8 -*- import requests import linecache impor ...
- scrapy实例:爬取中国天气网
1.创建项目 在你存放项目的目录下,按shift+鼠标右键打开命令行,输入命令创建项目: PS F:\ScrapyProject> scrapy startproject weather # w ...
随机推荐
- [CF664A]Complicated GCD(数论)
题目链接 http://codeforces.com/problemset/problem/664/A 题意 给两个数,找出它们的最大公因子d,使得从a到b之间的数都可以整除d. 题解 结论: 当gc ...
- native到CPU
Native 所谓的native准确的说是借由虚拟机实现的JNI接口调用的操作系统提供的API JNI使得class中的ACC_NATIVE标至的方法能借由JNI类的实例转换为JNI规范(如全限定名) ...
- hystrix(4) 异常降级
当执行HystrixCommand时,如果发生命令执行异常.熔断器熔断.信号量超过数量,就会执行降级fallback方法,并返回结果.本质上,当出现以上情况是,执行fallback方法,而不是run方 ...
- 实验 3:Mininet 实验——测量路径的损耗率
实验目的 在实验 2 的基础上进一步熟悉 Mininet 自定义拓扑脚本,以及与损耗率相关的设 定:初步了解 Mininet 安装时自带的 POX 控制器脚本编写,测试路径损耗率. 实验任务 h0 向 ...
- Unity 如何在窗口大小可以随意改变的情况下让游戏世界完整的显示在镜头中
当我们开发游戏时,如果是开发手机游戏,屏幕窗口的比例是固定的,不会说在运行时改变的. 但是,PC端的游戏就不一定,我希望它能被用户随意拉扯,但完整的内容还是能显示出来,这里我直接放例子: 请注意黑色的 ...
- breakpad系列(1)——起步
原文来自breakpad目录中doc目录下的getting_started_with_breakpad文档,建议去看原文! 介绍 Breakpad是一个比Linux core机制更强大的.用于记录程序 ...
- Docker 容器化部署 Python 应用
Docker 是一个开源项目,为开发人员和系统管理员提供了一个开放平台,可以将应用程序构建.打包为一个轻量级容器,并在任何地方运行.Docker 会在软件容器中自动部署应用程序. 在本篇中,我将介绍如 ...
- css定位于xpath的区别
css选择 是依据页面的数据样式定位的, 有标签选择, 类选择, id选择, 或者他们的交并集, 除此之外没有其他的辅助元素了 xpath 是路径表达式,所有元素和内容都可以成为路径的一部分. 两 ...
- Artwork (Gym - 102346A)【DFS、连通块】
Artwork (Gym - 102346A) 题目链接 算法 DFS,连通块 时间复杂度:O(k*n + k * k) 1.这道题就是让你判断从(0,0)到(m,n),避开中途所有的传感器(传感器的 ...
- spring-boot autoConfiguration
一, 第一个待注入类 public class CacheService { } public class LoggerService { } 方法一, 实现接口ImportSelectort pub ...