GIANPAOLO

这里有个苹果

斯是陋室

爬取课程表和要闻

 

先模拟登入后,截取的html里面没有想要的数据,在network中找到想要的数据所在的url。用正则表达式在一开始获取的页面先获取id。

session = requests.session()
    resp1 = session.post(url, data=formDate, headers=headers)
    html=resp1.text
    top=re.search(r'top\.aspx\?id=\d+',html).group()#获取想要的id
    num=re.search(r'=\d+',top).group()[1:]

 

然后根据请求头信息更改原先的请求头。再次获取信息,就得到需要的数据。

 

default=url2+'dafault.aspx?id='+num
    right=url2+'right.aspx?id='+num
    headers1=headers
    headers1['Referer']=default
    resp2=session.get(right,headers=headers1)
    html=resp2.text

然后用beautifulsoup解析html提取文字信息。并保存进数据库。

soup=BeautifulSoup(html,'lxml')
    soup=soup.select('table')
    soup1=soup[4].find_all('tr')
    kcb = {
        '1':'',
        '2':"",
        '3':'',
        '4':'',
        '5': '',
        '6': '',
        '7': '',
        '8':'',
        '9': ''
    }
    for i in range(1,12) :
        k=1
        flag=0
        for  t in soup1[i]:
            t=str(t)
            t1=re.sub('<a.*?</td>','',t,re.S)
            t1=BeautifulSoup(t1,'lxml')
            print(t1.text)
            if((t1.text=="上午" or t1.text=="下午" or t1.text=="晚上")and k==1):

                flag=1
            if(flag==1):
                kcb[str(k)] = t1.text
            else:
                kcb[str(k+1)] = t1.text
            print(k)
            k=k+1
        save_mysql(kcb)

 

写要闻的爬取就是在网页源码中可以看到阅读数以为就可以爬取,结果一直是none,于是想阅读时要不断跟新就想到ahr中找找,就在netwrok的ahr选项中找到的,

用正则把需要的id值抓取下来给新的url去获取阅读数。

 m =doc('.detail_main_content script').text()
        a = re.search(r'\?id=\d+',m).group()
        url1 = 'http://news.fzu.edu.cn/interFace/getDocReadCount.do'+a
        read = pq(url=url1)

写mysql的时候一直发生异常。一定一定要注意语法的正确。被这个坑了一个下午

 try:
        connect = pymysql.connect(
            host="localhost",
            user='root',
            password='root',
            db="ddz",
            charset='utf8',
            port=3306
        )
        mycursor = connect.cursor(pymysql.cursors.DictCursor)
        sql ='insert into yaowen(count,title,fbsj,author,content)value(%s,%s,%s,%s,%s)'
        mycursor.execute(sql,( contents['readcount'],contents['title'],contents['fbsj'] , contents['author'],contents['content']))
        connect.commit()
        print('成功插入', mycursor.rowcount, '条数据')
    except Exception:
        connect.rollback()
        print('发生异常')
    mycursor.close()
    connect.close()

 

posted @ 2021-01-04 19:41  Gianpaolo  阅读(68)  评论(0)    收藏  举报