加载中…
个人资料
周叶舟
周叶舟
  • 博客等级:
  • 博客积分:0
  • 博客访问:20,336
  • 关注人气:548
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Python实现网页敏感词批量查找

(2020-02-02 13:49:04)
标签:

python

代码

本例要查找的网页保存在”D:\test.xlsx”文件中第一列,要查找的敏感词为“第一”“质量”“最”(可根据实际需要修改敏感词内容和数量),运行代码后查找结果保存在”D:\test.xlsx”文件中第二列,以下代码已经在Python27中调试通过:

#coding=utf-8

import os
import re
import requests

from requests import exceptions
from openpyxl import Workbook
from openpyxl import load_workbook


def get_html(url):
    headers = {
       
'User-Agent': 'Mozilla/5.0(Windows NT 10.0; WOW64; Trident/7.0; rv:11.0)\
    like Gecko'
   
# 模拟浏览器访问
   
i = 0
   
t1=10
   
while i < 3: #三次重连
    
try:
         r = requests.get(url
,timeout=t1, headers = headers)       #请求访问网站
        
r.raise_for_status()
         r.encoding = r.apparent_encoding
        
#print(r.status_code)
        
if r.status_code == 200:
           
return r.text
        
else:
            
return ''
    
except requests.RequestException as e:
        
print(e)
       
#print(url)
        
return ''
    
i += 1

def rexcel(excelFile): #excel文件
   
list1 = []
   
if not os.path.exists(excelFile):
       
print("文件不存在")
       
return list1
    wb = load_workbook(excelFile)
    ws = wb.active
   
for j in range(ws.max_row):
           r = j +
1
          
list1.append(ws.cell(row=r, column=1).value)
   
return  list1

def wexcel(excelFile,list2): #excel文件
   
if not os.path.exists(excelFile):
       
print("文件不存在")
       
return 0
   
wb = load_workbook(excelFile)
    ws = wb.active
   
for row in range(len(list2)):
        
#print(row)
       
r = row + 1
       
ws.cell(row=r, column=2).value = list2[row]
       
if row>1048575:
           
break
   
wb.save(excelFile)
   
return  1



if __name__ == '__main__': #程序入口
   
excelFile = 'D:/test.xlsx'
   
list1=rexcel(excelFile)
   
#print(list1[2])
   
pattern = \
       
ur'([\u4e00-\u9fa5]{1,}(第一|质量|))' #敏感词之间用|分隔
   
re_compile = re.compile(pattern)

    list2 = []
   
for m in range(len(list1)):
        content =
''
       
s1=list1[m]
       
if s1==None:
           
break

        if
s1[0:4]=='http':
            webcontent = get_html(s1)
       
else:
           
continue
           
#print webcontent
       
if webcontent == '':
             list2.append(
u'获取页面数据失败')
            
continue
        else
:
            
for n in re_compile.finditer(webcontent):
                   content = content + n.group() +
';'

            
list2.append(content)
           
#print(list2)
   
wexcel(excelFile,list2)

 


运行后的”D:\test.xlsx”文件如下图:

 Python实现网页敏感词批量查找


0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有