需求:爬取网站上的公司信息

代码如下:

import json
import os
import shutil
import requests
import re
import time requests.packages.urllib3.disable_warnings() #通过url请求接口,获取返回数据
def getPage(url,headers):
try:
response = requests.get(url=url, headers=headers, verify=False)
response.encoding = 'utf-8'
if response.status_code == 200:
#print (response.text)
return response.text
else:
print('请求异常:{} status:{}'.format(url, response.status_code))
except Exception as e:
print('请求异常: {} error: {}'.format(url, e))
return None #删除文件的重复行
def file2uniq(file,destpath):
sum = 0
sum_pre = 0
addrs = set()
with open(file, 'r',encoding='utf8') as scan_file:
for line in scan_file.readlines():
sum_pre += 1
# addr = get_addr(line)
# line.decode('utf8')
addrs.add(line)
scan_file.close()
with open(destpath, 'w',encoding='utf8') as infile:
while len(addrs) > 0:
sum += 1
infile.write(addrs.pop())
infile.close() if (os.path.exists(file)):
os.remove(file)
try:
os.rename(destpath, file)
except Exception as e:
print (e)
print ('rename file fail\r')
else:
print ('rename file success\r')
#print(addrs)
print("去重之前文本条数: "+str(sum_pre))
print("去重之后文本条数: "+str(sum))
return sum_pre,sum #通过正则表达式提取页面内容
def parseHtml(html):
#pattern = re.compile(r'<tr> <td class="tx">.+\s(.+)', re.I) # 不区分大小写 匹配股票名称 # 不区分大小写 获取完整公司名
pattern = re.compile(r'<td class="text-center">.+</td> <td> <a href="/firm_.+">\s(.+)', re.I) # 获取证券公司
#pattern = re.compile(r'\t(.+)[\s]+</a> </td> <td class="text-center">.+</td> <td class="text-center">.+</td> </tr>', re.I)
#pattern = re.compile(r'\t(.+)\s\t\t\t\t\t\t\t </a> </td> <td class="text-center">.+</td> <td class="text-center">.+</td> </tr> <tr> <td class="tx">', re.I) # 不区分大小写
#pattern = re.compile(r'</a>\s</td>\s<td class="text-center">.+</td> <td> <a href="/firm_.+.html">\s(.+)[\s]+</a> </td> <td> <a href="/firm_.+.html">\s(.+)', re.I) # 不区分大小写 匹配股票名称 items = re.findall(pattern, html)
#print (items)
for item in items:
yield {
'orgName': item.strip(),
} def write2txt(content):
with open(file, 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n') def removeStr(old_str,new_str):
"""
with open('sanban.txt', 'a', encoding='utf-8') as fpr:
content = fpr.read()
content = content.replace(r'{"orgName": "', '')
content = content.replace(r'"}', '')
"""
file_data = ""
with open(file, 'r', encoding='utf-8') as f:
for line in f:
if old_str in line:
line = line.replace(old_str,new_str)
file_data += line
with open(file, 'w', encoding='utf-8') as f:
f.write(file_data) def main(page):
#url = 'https://www.qichacha.com/elib_sanban.html?p=' + str(page)
url = 'https://www.qichacha.com/elib_ipo.html?p=' + str(page) # https://www.qichacha.com/elib_ipo.html?p=2
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
}
print (url)
html = getPage(url,headers)
#print (html)
for item in parseHtml(html):
print(item)
write2txt(item)
removeStr(r'{"orgName": "','')
removeStr(r'"}', '') file2uniq(file, destpath) if __name__ == '__main__':
file = r'orgName.txt'
#file = r'midOrg.txt'
#sourcepath = r'sanban.txt'
destpath = r'temp.txt'
for page in range(1,2):
main(page)
time.sleep(1)

python爬取网业信息案例的更多相关文章

  1. Python爬取网易云音乐歌手歌曲和歌单

    仅供学习参考 Python爬取网易云音乐网易云音乐歌手歌曲和歌单,并下载到本地 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做 ...

  2. 用Python爬取网易云音乐热评

    用Python爬取网易云音乐热评 本文旨在记录Python爬虫实例:网易云热评下载 由于是从零开始,本文内容借鉴于各种网络资源,如有侵权请告知作者. 要看懂本文,需要具备一点点网络相关知识.不过没有关 ...

  3. Python爬取网易云热歌榜所有音乐及其热评

    获取特定歌曲热评: 首先,我们打开网易云网页版,击排行榜,然后点击左侧云音乐热歌榜,如图: 关于如何抓取指定的歌曲的热评,参考这篇文章,很详细,对小白很友好: 手把手教你用Python爬取网易云40万 ...

  4. Python 爬取网易云歌手的50首热门作品

    使用 requests 爬取网易云音乐 Python 代码: import json import os import time from bs4 import BeautifulSoup impor ...

  5. Python爬取网易云歌单

    目录 1. 关键点 2. 效果图 3. 源代码 1. 关键点 使用单线程爬取,未登录,爬取网易云歌单主要有三个关键点: url为https://music.163.com/discover/playl ...

  6. 爬虫实战(二) 用Python爬取网易云歌单

    最近,博主喜欢上了听歌,但是又苦于找不到好音乐,于是就打算到网易云的歌单中逛逛 本着 "用技术改变生活" 的想法,于是便想着写一个爬虫爬取网易云的歌单,并按播放量自动进行排序 这篇 ...

  7. Python爬取拉勾网招聘信息并写入Excel

    这个是我想爬取的链接:http://www.lagou.com/zhaopin/Python/?labelWords=label 页面显示如下: 在Chrome浏览器中审查元素,找到对应的链接: 然后 ...

  8. python爬取豆瓣视频信息代码

    目录 一:代码 二:结果如下(部分例子)   这里是爬取豆瓣视频信息,用pyquery库(jquery的python库). 一:代码 from urllib.request import quote ...

  9. python爬取网易云音乐歌曲评论信息

    网易云音乐是广大网友喜闻乐见的音乐平台,区别于别的音乐平台的最大特点,除了“它比我还懂我的音乐喜好”.“小清新的界面设计”就是它独有的评论区了——————各种故事汇,各种金句频出.我们可以透过歌曲的评 ...

随机推荐

  1. C# 生成全球唯一标识符GUID

    string strguid = Guid.NewGuid().ToString();//57d99d89-caab-482a-a0e9-a0a803eed3ba 生成标准的标志符 (36位标准)st ...

  2. .net core控制台程序中使用原生依赖注入

    如果要在程序中使用DbContext,则需要先在Nuget中安装Microsoft.EntityFrameworkCore.SqlServer using ConsoleApp1.EntityFram ...

  3. Supermap/Cesium 开发心得----获取三维视角的四至范围

    网上目前有两种获取当前Camera的四至范围的方法 方法一    这种方法是最通用的,即使在哥伦布视角(2.5D下依旧能准确获取值) function getCurrentExtent() { // ...

  4. 拖动条(SeekBar)的功能与用法

    拖动条和进度条非常相似,只是进度条采用颜色填充来表明进度完成的程度,而拖动条则通过滑块的位置来标识数值——而且拖动条允许用户拖动滑块来改变值,因此拖动条通常用于对系统的某种数值进行调节,比如调节音量等 ...

  5. bayaim——听课笔记_01.Docker基础应用 10课.txt

    ===========2019年8月5日18:39:06====================10.20.100.21rootbayaim ==========01-Docker介绍======== ...

  6. vue组件之间的通信方式

    组件之间的通信方式有很多种 这里分享4种组件之间的通信方式 props(主要是父传子)  自定义事件(主要是子传父)  pubsub消息订阅与发布  xuex 1.props和自定义事件 app.vu ...

  7. 文件上传报错:Unknown: file created in the system's temporary directory

    nginx+php下文件上传成功,但会有错误提示如下: <b>Notice</b>:  Unknown: file created in the system's tempor ...

  8. Localize UI Elements 汉化界面(本地化)

    In this lesson, you will learn the basics of localizing visible UI elements. By default, the applica ...

  9. docker升级步骤及注意事项

    centos系统默认安装的docker版本是1.13版本,在安装部分镜像时可能出现兼容问题,本文通过实际操作总结Docker升级最新版本步骤及可能出现的问题,供各位参考. 环境:CentOS Linu ...

  10. Markdown语法教程

    标题 # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题 效果如下: 一级标题 二级标题 三级标题 四级标题 五级标题 六级标题 段落 换 ...