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

代码如下:

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. SpringBoot整合dubbo(yml格式配置)

    yml文件 如果只作为服务的消费者不用暴露端口号,扫描的包名根据自己service改 dubbo: application: name: springboot-dubbo-demo #应用名 regi ...

  2. 松软科技Web课堂:JavaScript While 循环

    只要条件为 true,循环能够一直执行代码块. While 循环 while 循环会一直循环代码块,只要指定的条件为 true. 语法 while (条件) { 要执行的代码块 } 实例 在下面的例子 ...

  3. Asp.Net MVC Webapi Eventsource 实现时效消息

    ApiController 后端API public System.Net.Http.HttpResponseMessage GetUnknownNotices() { var user = Form ...

  4. python 打飞机项目 ( 基类封装 )

    项目代码 | plane # -*- coding:utf-8 -*- import pygame, time from Plane import Plane from HeroPlane impor ...

  5. Java 学习之路让我帮助很大的书籍

    笔主目前从事Java工作已经5年,满打满算下来,从大二上学期接触 Java 到现在也快走过了 7 个年头.在学习 Java 过程中,网上的一些视频还有一些书籍对我帮助都很大.下面就我自己看过的一些书籍 ...

  6. 前端小白webpack学习(二)

    前一篇写了自我总结的webpack定义:为JavaScript服务的静态模块打包器 和几大基本概念 entry.output.plugins.loaders等.指路前端小白webpack学习(一) 下 ...

  7. Password Management:Password in Configuration File 密码管理:配置文件中的密码

  8. React的setState学习及应用

    React的setState学习及应用 一:作用: setState() 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件.这是用于更新 ...

  9. PHP服务化搭建之nginx动静分离实战

    如有什么问题可以加群交流:647617935 什么是动静分离 动静分离:将项目中的CSS,JS,HTML,JPG'.等静态资源和 PHP等动态资源分开处理的一种方式 动静分离优点 不同的文件由不同类型 ...

  10. 剑指offer笔记面试题6----从未到头打印链表

    题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值.链表节点定义如下: struct ListNode{ int m_nKey; ListNode* m_pNext; } 测试用例: 功能测 ...