2020学习 04 python 爬取某政府网站信件

直接上代码⑧:

#coding:utf-8
import requests
from lxml import etree
import time
import pymysql
import datetime
import urllib
import json
from IPython.core.page import page

conn = pymysql.connect(
        host="localhost",
        user="root",
        port=3306,
        password="123456",
        database="bjxj")
gg=2950

def db(conn, reqcontent,reqname,reqtime,resname,restime,rescontent,reqtype,isreply):
    cursor = conn.cursor()
    # cursor.execute(
    #     "INSERT INTO xinjian(name) VALUES (%s)",
    #     [name])
    if isreply == False :
        isreply = 0
        restime1 = ‘‘
    else :
        isreply = 1
        restime1 = restime[0]
    print(reqcontent)
    print(reqname)
    print(reqtime)
    print(resname)
    #print(restime)
    print(rescontent)
    print(reqtype)
    print(isreply)
    cursor.execute("INSERT INTO aaa (reqcontent,reqname,reqtime,resname,rescontent,reqtype,isreply,restime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);", [reqcontent,reqname,reqtime,resname,rescontent,reqtype,isreply,restime1])
    conn.commit()
    cursor.close()

def dbservice(conn,username,sp,image,pr):
    cursor = conn.cursor()
    #https://search.jd.com/Search?keyword=%E5%8C%96%E5%A6%86&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E5%8C%96%E5%A6%86&stock=1&page=3&s=59&click=0
    #https://search.jd.com/Search?keyword=%E5%8C%96%E5%A6%86&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E5%8C%96%E5%A6%86&stock=1&page=5&s=113&click=0
    global gg
    created=datetime.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘)
    created2=datetime.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘)
    num=512
    cid=319

    image1="http:"+image
    image="http://localhost:8089/pic/phone/"+str(gg)+".jpg"
    print(image1)
    urllib.request.urlretrieve(image1,‘e:/JDpic/‘+str(gg)+‘.jpg‘)
    print(username)
    cursor.execute("INSERT INTO tb_item(title,id,sell_point,price,num,image,cid,created,updated) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);", [username,gg,sp,pr,num,image,cid,created,created2])

    conn.commit()
    cursor.close()

    gg=gg+1
def crow_first(n):
    url=‘https://search.jd.com/Search?keyword=%E5%8C%96%E5%A6%86&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&stock=1&page=‘+str(n)+‘&s=‘+str(1+(n-1)*30)+‘&click=0&scrolling=y‘
    print(url)
    head = {‘authority‘: ‘search.jd.com‘,
            ‘method‘: ‘GET‘,
            ‘path‘: ‘/s_new.php?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&cid2=653&cid3=655&page=4&s=84&scrolling=y&log_id=1529828108.22071&tpl=3_M&show_items=7651927,7367120,7056868,7419252,6001239,5934182,4554969,3893501,7421462,6577495,26480543553,7345757,4483120,6176077,6932795,7336429,5963066,5283387,25722468892,7425622,4768461‘,
            ‘scheme‘: ‘https‘,
            ‘referer‘: ‘https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&cid2=653&cid3=655&page=3&s=58&click=0‘,
            ‘user-agent‘: ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36‘,
            ‘x-requested-with‘: ‘XMLHttpRequest‘,
            ‘Cookie‘:‘qrsc=3; pinId=RAGa4xMoVrs; xtest=1210.cf6b6759; ipLocation=%u5E7F%u4E1C; _jrda=5; TrackID=1aUdbc9HHS2MdEzabuYEyED1iDJaLWwBAfGBfyIHJZCLWKfWaB_KHKIMX9Vj9_2wUakxuSLAO9AFtB2U0SsAD-mXIh5rIfuDiSHSNhZcsJvg; shshshfpa=17943c91-d534-104f-a035-6e1719740bb6-1525571955; shshshfpb=2f200f7c5265e4af999b95b20d90e6618559f7251020a80ea1aee61500; cn=0; 3AB9D23F7A4B3C9B=QFOFIDQSIC7TZDQ7U4RPNYNFQN7S26SFCQQGTC3YU5UZQJZUBNPEXMX7O3R7SIRBTTJ72AXC4S3IJ46ESBLTNHD37U; ipLoc-djd=19-1607-3638-3638.608841570; __jdu=930036140; user-key=31a7628c-a9b2-44b0-8147-f10a9e597d6f; areaId=19; __jdv=122270672|direct|-|none|-|1529893590075; PCSYCityID=25; mt_xid=V2_52007VwsQU1xaVVoaSClUA2YLEAdbWk5YSk9MQAA0BBZOVQ0ADwNLGlUAZwQXVQpaAlkvShhcDHsCFU5eXENaGkIZWg5nAyJQbVhiWR9BGlUNZwoWYl1dVF0%3D; __jdc=122270672; shshshfp=72ec41b59960ea9a26956307465948f6; rkv=V0700; __jda=122270672.930036140.-.1529979524.1529984840.85; __jdb=122270672.1.930036140|85.1529984840; shshshsID=f797fbad20f4e576e9c30d1c381ecbb1_1_1529984840145‘
            }
    r = requests.get(url, headers=head)
    r.encoding=‘utf-8‘
    html = r.content
    html1 = etree.HTML(html)
    #print(html1)
    datas=html1.xpath(‘//li[contains(@class,"gl-item")]‘)
    s2=0

    for data in datas:
            s2=s2+1;
            p_price = data.xpath(‘div/div[@class="p-price"]/strong/i/text()‘)
            p_comment = data.xpath(‘div/div[@class="p-commit"]/strong/a/text()‘)
            p_name = data.xpath(‘div/div[@class="p-name p-name-type-2"]/a/em/text()‘)
            p_sell_point = data.xpath(‘div/div[@class="p-name p-name-type-2"]/a/i/text()‘)
            p_image= data.xpath("div[@class=‘gl-i-wrap‘]/div[@class=‘p-img‘]/a/img/@source-data-lazy-img")
            dbservice(conn,"".join(p_name),"".join(p_sell_point),"".join(p_image),"".join(p_price))
            if len(p_price) == 0:
                p_price = data.xpath(‘div/div[@class="p-price"]/strong/@data-price‘)
    print(s2)
def shijinOU(json1,url,i):
    print(i)
    head = {
            ‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36‘,
            ‘method‘: ‘POST‘,
            ‘Content-Type‘: ‘application/json;charset=UTF-8‘,

            }
    data_json = json.dumps(json1)
    r = requests.post(url,data = data_json,headers=head)
    html = r.content.decode("utf-8")
    print("Status code:",r.status_code)
    new_data = json.loads(html)
    print("6666:" + html)
    for s in range(0,6):
        print(new_data[‘mailList‘][s])
        if new_data[‘mailList‘][s][‘letter_type‘] == ‘咨询‘ :
            reqname = new_data[‘mailList‘][s][‘letter_title‘]
            reqtime = new_data[‘mailList‘][s][‘create_date‘]
            resname = new_data[‘mailList‘][s][‘org_id‘]
            isreply = new_data[‘mailList‘][s][‘isReply‘]
            reqtype = new_data[‘mailList‘][s][‘letter_type‘]
            #print(isreply)
            #print("询问标题:" + reqname + "询问时间:" + reqtime + "回答部门:" + resname + "是否回答:")
            zixunTiqu(new_data[‘mailList‘][s][‘original_id‘],reqname,reqtime,resname,isreply,reqtype)

        #if new_data[‘mailList‘][s][‘letter_type‘] == ‘建议‘ :

        #break
        #if new_data[‘mailList‘][s][‘letter_type‘] == ‘投诉‘ :

def zixunTiqu(AH,reqname,reqtime,resname,isreply,reqtype):
    #print("询问标题:"+reqname+"询问时间:"+reqtime+"回答部门:"+resname+"是否回答:"+isreply)
    head = {
            ‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36‘,
            ‘method‘: ‘GET‘
        }
    url2 = ‘http://www.beijing.gov.cn/hudong/hdjl/com.web.consult.consultDetail.flow?originalId=‘+AH      

    r = requests.get(url2, headers=head)
    print(r.status_code)

    html = r.content.decode("utf-8")
    #print("777"+html)
    html1 = etree.HTML(html)
    #print(html)
    datas=html1.xpath(‘.//form[@id="f_baner"]/div‘)
    result = ‘‘
    data = datas[0].xpath(‘//div[@class="col-xs-12 col-md-12 column p-2 text-muted mx-2"]//text()‘)[0]
    result = result + data.replace(‘\r‘, ‘‘).replace(‘\t‘, ‘‘).replace(‘\n‘, ‘ ‘)

    print("问题详细情况:" + result.strip() + "?")
    reqcontent = result.strip()
    restime = datas[1].xpath("//div/div/div[@class=‘col-xs-12 col-md-12 column o-border-bottom my-2‘]/div[@class=‘col-xs-12 col-md-12 column o-border-bottom2‘]/div[@class=‘col-xs-12 col-sm-3 col-md-3 my-2 ‘]//text()")
    print(restime)
    rescontents = datas[1].xpath("//div/div[@class=‘col-xs-12 col-md-12 column o-border-bottom my-2‘]/div[@class=‘col-xs-12 col-md-12 column p-4 text-muted my-3‘]//text()")
    #print(rescontents)

    resc = ‘‘
    for rescontent in rescontents:
        resc = resc+rescontent.replace(‘\r‘, ‘‘).replace(‘\t‘, ‘‘).replace(‘\n‘, ‘‘)
    print(resc)

    db(conn, result.strip(),reqname,reqtime,resname,restime,resc,reqtype,isreply)
if __name__==‘__main__‘:
    for i in range(0,100):
        print(‘***************************************************‘)
        page = 6*i

        fuck = {"PageCond/begin":page,
                "PageCond/length":6,
                "PageCond/isCount":"true",
                "keywords":"","orgids":"",
                "startDate":"","endDate":"",
                "letterType":"","letterStatue":""
                }
        shijinOU(fuck,"http://www.beijing.gov.cn/hudong/hdjl/com.web.search.mailList.mailList.biz.ext",i)
        #sbreak
        #print(fuck)

  爬取结果如图:

原文地址:https://www.cnblogs.com/xcl666/p/12262277.html

时间: 2025-01-07 09:49:59

2020学习 04 python 爬取某政府网站信件的相关文章

python入门学习之Python爬取最新笔趣阁小说

Python爬取新笔趣阁小说,并保存到TXT文件中      我写的这篇文章,是利用Python爬取小说编写的程序,这是我学习Python爬虫当中自己独立写的第一个程序,中途也遇到了一些困难,但是最后迎刃而解了.这个程序非常的简单,程序的大概就是先获取网页的源代码,然后在网页的源代码中提取每个章节的url,获取之后,在通过每个url去获取文章的内容,在进行提取内容,然后就是保存到本地,一TXT的文件类型保存.大概是这样1:获取网页源代码2:获取每章的url3:获取每章的内容4:下载保存文件中 1

Python爬取知乎网站

1 import urllib.request 2 import re 3 4 url = 'http://daily.zhihu.com/' 5 def get_html(url): 6 html = urllib.request.urlopen(url).read() 7 html = html.decode('utf-8') 8 return html 9 10 def get_url_num(html): 11 res = re.compile('<a href="/story/(

使用python爬取csdn博客访问量

最近学习了python和爬虫,想写一个程序练练手,所以我就想到了大家都比较关心的自己的博客访问量,使用python来获取自己博客的访问量,这也是后边我将要进行的项目的一部分,后边我会对博客的访问量进行分析,以折线图和饼图等可视化的方式展示自己博客被访问的情况,使自己能更加清楚自己的哪些博客更受关注,博客专家请勿喷,因为我不是专家,我听他们说专家本身就有这个功能. 一.网址分析 进入自己的博客页面,网址为:http://blog.csdn.net/xingjiarong 网址还是非常清晰的就是cs

爬虫学习 04.Python网络爬虫之requests模块(1)

爬虫学习 04.Python网络爬虫之requests模块(1) 引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档症.抑郁.头疼.甚至死亡. 今日概要 基于requests的get请求 基于requests模块的post请求 基于requests模块ajax的get请求 基于requests模块ajax的post请求 综合项目练习:爬取国家药品监

都说抖音是毒品软件?我用Python爬取了里面的小视频!

简介 抖音,是一款可以拍短视频的音乐创意短视频社交软件,该软件于2016年9月上线,是一个专注年轻人的15秒音乐短视频社区.用户可以通过这款软件选择歌曲,拍摄15秒的音乐短视频,形成自己的作品.此APP已在Android各大应用商店和APP Store均有上线. 今天咱们就用Python爬取抖音视频 获得视频播放地址 查询的用户ID 视频名字列表 视频链接列表 用户昵称 获得带水印的视频播放地址 video_url:带水印的视频播放地址 download_url: 带水印的视频下载地址 视频下载

没有内涵段子可以刷了,利用Python爬取段友之家贴吧图片和小视频(含源码)

由于最新的视频整顿风波,内涵段子APP被迫关闭,广大段友无家可归,但是最近发现了一个"段友"的app,版本更新也挺快,正在号召广大段友回家,如下图,有兴趣的可以下载看看(ps:我不是打广告的,没收广告费的) 同时,之前同事也发了一个贴吧的段子聚居地,客官稍等,马上奉上连接:段友之家?https://tieba.baidu.com/f?ie=... 然后呢,看到上面,确实好多段友在上面,于是乎,我就想爬取他们的图片和小视频,就有了这篇文章的主题: 其实吧,用Python爬取网站数据是最基

python爬取B站千万级数据,发现了这些热门UP主的秘密!

Python(发音:英[?pa?θ?n],美[?pa?θɑ:n]),是一种面向对象.直译式电脑编程语言,也是一种功能强大的通用型语言,已经具有近二十年的发展历史,成熟且稳定.它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务.它的语法非常简捷和清晰,与其它大多数程序设计语言不一样,它使用缩进来定义语句. Python支持命令式程序设计.面向对象程序设计.函数式编程.面向切面编程.泛型编程多种编程范式.与Scheme.Ruby.Perl.Tcl等动态语言一样,Python具备垃圾回收

分手后,小伙怒用Python爬取上万空姐照片,赢取校花选举大赛!

首先展示下Python爬取到的成果:   我做什么都要争第一,这次的校花投票选举大赛也不例外,虽然我是个男的......但是我看到了前女友竟然已经有三百多票排到第三名了,我怎么能眼睁睁的看着她优秀呢?我必须要让她排到前三除外,·不行,必须是前十开外!我想到一个办法就是用Python开发一个百度爬虫,爬取百度所有美女的照片,然后申请多个账号进行参赛.   其实比起Python爬取图片外,我对微信上的投票小程序也有所研究,已经有了Python实现微信上刷票脚本的思路,这个我下次再分享大家,这次先学习

Python 爬取笔趣阁小说

最近在学习 Python,觉得爬虫很好玩,今天我准备爬取我看了至少三遍的小说<雪中悍刀行>,作者是烽火戏诸侯,他的小说很有才华,有着很多的粉丝,但他很多部小说都处于断更状态,因此人称大内总管. 我准备爬取小说的网站是新笔趣阁,这里一个盗版网站,是名门正派的眼中钉,不过对于我这种不想交钱看小说的人,没资格评论它,这个网站连载的小说更新的还是比较快的,内容都是和正版的内容一模一样.好了,废话不多说了,下面开始放代码: 我在抓取小说内容时先用了 requests 库来抓取,结果就抓到了一章小说的开头