python采集百度搜索结果带有特定URL的链接代码实例

yipeiwu_com5年前Python基础

这篇文章主要介绍了python采集百度搜索结果带有特定URL的链接代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

#coding utf-8
import requests
from bs4 import BeautifulSoup as bs
import re
from Queue import Queue
import threading
from argparse import ArgumentParser

arg = ArgumentParser(description='baidu_url_collet py-script by xiaoye')
arg.add_argument('keyword',help='keyword like inurl:?id=for searching sqli site')
arg.add_argument('-p','--page',help='page count',dest='pagecount',type=int)
arg.add_argument('-t','--thread',help='the thread_count',dest='thread_count',type=int,default=10)
arg.add_argument('-o','--outfile',help='the file save result',dest='oufile',type=int,default='result.txt')
result = arg.parse_args()
headers = {'User-Agent':'Mozilla/5.0(windows NT 10.0 WX64;rv:50.0) Gecko/20100101 Firefox/50.0'}

class Bg_url(threading.Thread):
  def __init__(self,que):
    threading.Thread.__init__(self)
    self._que = que
  def run(self):
    while not self._que.empty():
      URL = self._que.get()
      try:
        self.bd_url_collet(URL)
      except Exception,e:
        print(e)
        pass
  def bd_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标签的链接
    for bq in bqs:
      r = requests.get(bq['href'], headers=headers, timeout=3)#获取真实链接
      if r.status_code == 200:#如果状态码为200
        print r.url
        with open(result.outfile, 'a') as f:
          f.write(r.url + '\n')
def main():
  thread = []
  thread_count = result.thread_count
  que = Queue()
  for i in range(0,(result.pagecount-1)*10,10):
  que.put('https://www.baidu.com/s?wd=' + result.keyword + '&pn=' + str(i))
  or i in range(thread_count):
  thread.append(Bd_url(que))
  for i in thread:
    i.start()
  for i in thread:
    i.join()    
if __name__ == '__main__':
  main()  
#执行格式
python aaaaa.py "inurl:asp?id=" -p 30 -t 30

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python开发的十个小贴士和技巧及长常犯错误

下面是十个Python中很有用的贴士和技巧。其中一些是初学这门语言常常会犯的错误。 注意:假设我们都用的是Python 3 1. 列表推导式 你有一个list:bag = [1, 2,...

python删除字符串中指定字符的方法

最近开始学机器学习,学习分析垃圾邮件,其中有一部分是要求去除一段字符中的标点符号,查了一下,网上的大多很复杂例如这样 import re temp = "司法局让我和户 1 5....

详解python并发获取snmp信息及性能测试

python & snmp 用python获取snmp信息有多个现成的库可以使用,其中比较常用的是netsnmp和pysnmp两个库。网上有较多的关于两个库的例子。 本文重点在于如何并...

python smtplib模块发送SSL/TLS安全邮件实例

python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。 smtp协议的基本命令包括: HELO 向服务器标识用户身份 MAIL 初始化邮件传输...

python实现宿舍管理系统

python实现宿舍管理系统

Python综合应用——宿舍管理系统,供大家参考,具体内容如下/p> 通过对 python 的函数,变量的应用,编写简单的关系系统 实现功能: 1.新增学生 2.显示全部学生信息...