python 线程池 分配任务给线程,爬取加入库。

该博客介绍了如何使用Python的线程池(ThreadPool)来并发地从多个URL获取网页内容。通过requests库获取HTML,正则表达式解析页面元素,然后遍历关键字列表,计算每个关键字在网页文本中的出现次数,并将结果存储到数据库中。最后更新数据库中的批次号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
from guanjianzi import keylist as keys
import re
from conMySql import ConDb
from multiprocessing.dummy import Pool as ThreadPool
s=requests.Session()
con=ConDb()
def getlist(url):
    html=s.get(url).content.decode()
    res=r'<li  class="li"><font class="date">(.*?)</font><a href="(.*?)" target="_blank">(.*?)</a><span class="new"></span></li>'
    li=re.findall(res,html)
    title=re.findall(r"<title>(.*?)</title>",html)[0]
    for x,y,z in li:
        y=url+str(y)
        y=re.sub(r"\/index\.html\.",'',y)
        html1=s.get(y).content.decode()
        text=str(html1)
        guanjianzi = {}
        num = 0
        for key in keys:  # 循环遍历关键字列表,查询关键字出现的次数
            count = text.count(key)  # count 关键字在本文中出现的次数
            if count > 0:
                guanjianzi.update({key: count})  # 把关键字和出现的次数添加到字典中
                num += count
        print(title,y,z,guanjianzi,num,x)
        sql='''  insert into urllist(source,urls,titles,keyname,keysum,date1) values('{}','{}','{}',"{}",'{}','{}') '''.format(title,y,z,guanjianzi,num,x)
        con.runSql(sql)
if __name__ == '__main__':
    urls = ['http://www.ndrc.gov.cn/xwzx/xwfb/index.html','http://www.ndrc.gov.cn/zwfwzx/zxgg/index.htmm','http://www.ndrc.gov.cn/zwfwzx/xzxknew/index.html','http://www.ndrc.gov.cn/zcfb/zcfbl/index.html','http://www.ndrc.gov.cn/zcfb/gfxwj/index.html','http://www.ndrc.gov.cn/zcfb/zcfbgg/index.html','http://www.ndrc.gov.cn/zcfb/zcfbghwb/index.html','http://www.ndrc.gov.cn/zcfb/zcfbtz/index.html','http://www.ndrc.gov.cn/zcfb/jd/index.html','http://www.ndrc.gov.cn/yjzq/index.html']
    t=ThreadPool(5)
    for url in urls:
        t.apply_async(getlist,args=(url,))
    t.close()
    t.join()
    sql1='select max(bat) from urllist limit 1'
    bat=con.runSql(sql1)[0][0]
    bat=int(bat)+1
    # print(bat)
    sql2="update urllist set bat='{}'".format(bat)
    con.runSql(sql2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值