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 爬取中国工业园网的更多相关文章

  1. Python爬取中国天气网

    Python爬取中国天气网 基于requests库制作的爬虫. 使用方法:打开终端输入 “python3 weather.py 北京(或你所在的城市)" 程序正常运行需要在同文件夹下加入一个 ...

  2. 初识python 之 爬虫:爬取中国天气网数据

    用到模块: 获取网页并解析:import requests,html5lib from bs4 import BeautifulSoup 使用pyecharts的Bar可视化工具"绘制图表& ...

  3. Python+Selenium爬取动态加载页面(1)

    注: 最近有一小任务,需要收集水质和水雨信息,找了两个网站:国家地表水水质自动监测实时数据发布系统和全国水雨情网.由于这两个网站的数据都是动态加载出来的,所以我用了Selenium来完成我的数据获取. ...

  4. selenium爬取煎蛋网

    selenium爬取煎蛋网 直接上代码 from selenium import webdriver from selenium.webdriver.support.ui import WebDriv ...

  5. Python+Selenium爬取动态加载页面(2)

    注: 上一篇<Python+Selenium爬取动态加载页面(1)>讲了基本地如何获取动态页面的数据,这里再讲一个稍微复杂一点的数据获取全国水雨情网.数据的获取过程跟人手动获取过程类似,所 ...

  6. Python Scrapy 爬取煎蛋网妹子图实例(一)

    前面介绍了爬虫框架的一个实例,那个比较简单,这里在介绍一个实例 爬取 煎蛋网 妹子图,遗憾的是 上周煎蛋网还有妹子图了,但是这周妹子图变成了 随手拍, 不过没关系,我们爬图的目的是为了加强实战应用,管 ...

  7. Python爬取中国票房网所有电影片名和演员名字,爬取齐鲁网大陆所有电视剧名称

    爬取CBO中国票房网所有电影片名和演员名字 # -*- coding: utf-8 -*- # 爬取CBO中国票房网所有电影片名 import json import requests import ...

  8. python爬取中国知网部分论文信息

    爬取指定主题的论文,并以相关度排序. #!/usr/bin/python3 # -*- coding: utf-8 -*- import requests import linecache impor ...

  9. scrapy实例:爬取中国天气网

    1.创建项目 在你存放项目的目录下,按shift+鼠标右键打开命令行,输入命令创建项目: PS F:\ScrapyProject> scrapy startproject weather # w ...

随机推荐

  1. Iterator泛型指针

    Iterator泛型指针 每个标准容器都提供一个名为: begin()的操作函数,返回一个iterator指向第一个元素: end()操作函数,返回一个iterator指向最后一个元素的下一位置: 定 ...

  2. CSS -- 盒子模型之边框、内边距、外边距

    一.使用border为盒子添加边框 盒子模型的边框就是围绕着内容及补白的线,这条线你可以设置它的粗细.样式和颜色(边框三个属性). 1.border-style(边框样式)常见样式有: dashed( ...

  3. [LeetCode] 46. 全排列(回溯)

    ###题目 给定一个没有重复数字的序列,返回其所有可能的全排列. 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], ...

  4. maven问题汇总

    Failed to read artifact descriptor for xxx:jar 在MyEclipse中执行Maven的install命令时,报“Failed to read artifa ...

  5. 预科班D11

    2020.09.21星期一 预科班D11 学习内容: 一.基本数据类型及内置方法 1.整形int及浮点型float + - * / // ** % > < >= <= 2.字符 ...

  6. TensorFlow之张量

    张量的概念 TensorFlow中的Tensor就是张量,张量是数学对象,是对标量.向量.矩阵的泛化.我们可以直接理解成张量就是列表,就是多维数组. 张量的维数用阶来表示: 0阶张量 标量 单个值 例 ...

  7. Redis学习(五)Redis知识点总结

    一.基础概念 Q:什么是 Redis? 定义:Redis 是完全开源免费基于内存亦可持久化的,遵守 BSD 协议,是一个高性能的 key-value 数据库. 特点: 数据的持久化 :可以将内存中的数 ...

  8. 分享一些好用的 Chrome 插件!

    使用浏览器扩展程序可以使你的工作效率提高数倍不止,那么下面我就向大家分享一下我日常使用的扩展,可能大多数扩展大家都已经在使用了,不过也难免有一两个是你不知道的. 以下排名并不分先后,请坚持看到最后,或 ...

  9. MyBatis学习(一)初识MyBatis

    一.MyBatis简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...

  10. Spring框架分为哪七大模块,各模块的主要功能作用是什么

    七大模块,如下: 1. Spring Core: Core封装包是框架的最基础部分,提供IOC和依赖注入特性.这里的基础概念是BeanFactory,它提供对Factory模式的经典实现来消除对程序性 ...