python采集百度搜索结果带有特定URL的链接代码实例
这篇文章主要介绍了python采集百度搜索结果带有特定URL的链接代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
#codingutf-8 importrequests frombs4importBeautifulSoupasbs importre fromQueueimportQueue importthreading fromargparseimportArgumentParser arg=ArgumentParser(description='baidu_url_colletpy-scriptbyxiaoye') arg.add_argument('keyword',help='keywordlikeinurl:?id=forsearchingsqlisite') arg.add_argument('-p','--page',help='pagecount',dest='pagecount',type=int) arg.add_argument('-t','--thread',help='thethread_count',dest='thread_count',type=int,default=10) arg.add_argument('-o','--outfile',help='thefilesaveresult',dest='oufile',type=int,default='result.txt') result=arg.parse_args() headers={'User-Agent':'Mozilla/5.0(windowsNT10.0WX64;rv:50.0)Gecko/20100101Firefox/50.0'} classBg_url(threading.Thread): def__init__(self,que): threading.Thread.__init__(self) self._que=que defrun(self): whilenotself._que.empty(): URL=self._que.get() try: self.bd_url_collet(URL) exceptException,e: print(e) pass defbd_url_collect(self,url): r=requests.get(url,headers=headers,timeout=3) soup=bs(r.content,'lxml',from_encoding='utf-8') bqs=soup.find_all(name='a',attrs={‘data-click‘:re.compile(r'.'),'class':None})#获得从百度搜索出来的a标签的链接 forbqinbqs: r=requests.get(bq['href'],headers=headers,timeout=3)#获取真实链接 ifr.status_code==200:#如果状态码为200 printr.url withopen(result.outfile,'a')asf: f.write(r.url+'\n') defmain(): thread=[] thread_count=result.thread_count que=Queue() foriinrange(0,(result.pagecount-1)*10,10): que.put('https://www.baidu.com/s?wd='+result.keyword+'&pn='+str(i)) oriinrange(thread_count): thread.append(Bd_url(que)) foriinthread: i.start() foriinthread: i.join() if__name__=='__main__': main() #执行格式 pythonaaaaa.py"inurl:asp?id="-p30-t30
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。