python如何才能获取src地址

Python019

python如何才能获取src地址,第1张

Copyright © 1999-2020, CSDN.NET, All Rights Reserved

python

打开APP

pergoods

关注

Python多线程爬取网站image的src属性实例 原创

2017-05-16 11:18:51

pergoods

码龄6年

关注

# coding=utf-8

'''

Created on 2017年5月16日

@author: chenkai

Python多线程爬取某单无聊图图片地址(requests+BeautifulSoup+threading+Queue模块)

'''

import requests

from bs4 import BeautifulSoup

import threading

import Queue

import time

class Spider_Test(threading.Thread):

def __init__(self,queue):

threading.Thread.__init__(self)

self.__queue = queue

def run(self):

while not self.__queue.empty():

page_url=self.__queue.get() [color=red]#从队列中取出url[/color]

print page_url

self.spider(page_url)

def spider(self,url):

r=requests.get(url) [color=red]#请求url[/color]

soup=BeautifulSoup(r.content,'lxml') [color=red]#r.content就是响应内容,转换为lxml的bs对象[/color]

imgs = soup.find_all(name='img',attrs={}) #查找所有的img标签,并获取标签属性值(为列表类型)

for img in imgs:

if 'onload' in str(img): [color=red]#img属性集合中包含onload属性的为动态图.gif,[/color]

print 'http:'+img['org_src']

else:

print 'http:'+img['src']

def main():

queue=Queue.Queue()

url_start = 'http://jandan.net/pic/page-'

for i in range(293,295):

url = url_start+str(i)+'#comment'

queue.put(url) [color=red]#将循环拼接的url放入队列中[/color]

threads=[]

thread_count=2 [color=red]#默认线程数(可自动修改)[/color]

for i in range(thread_count):

threads.append(Spider_Test(queue))

for i in threads:

i.start()

for i in threads:

i.join()

if __name__ == '__main__':[color=red] #在.py文件中使用这个条件语句,可以使这个条件语句块中的命令只在它独立运行时才执行[/color]

time_start = time.time()

main() [color=red]#调用main方法[/color]

print time.time()-time_start

[color=red]#背景知识[/color]

'''

q = Queue.Queue(maxsize = 10)

Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。

将一个值放入队列中

q.put(10)

调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为

1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。

将一个值从队列中取出

q.get()

调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。

'''

[color=red]如果想要下载图片需要

import urllib

再替换spider方法即可[/color]

def spider(self,url):

r=requests.get(url)

soup=BeautifulSoup(r.content,'lxml')

imgs = soup.find_all(name='img',attrs={})

urls=[]

for img in imgs:

if 'onload' in str(img):

print 'http:'+img['org_src']

urls.append('http:'+img['org_src'])

else:

print 'http:'+img['src']

url = urls.append('http:'+img['src'])

#下载图片

k=0

for urlitem in urls:

k+=1

if '.jpg' in urlitem:

urllib.urlretrieve(url=urlitem,filename='F:\image\\'+str(k)+'.jpg')

[color=red]-----------多线程访问百度实例[/color]

#coding:utf-8

import requests

import threading

import time

import sys

url = 'https://www.baidu.com'

def get_baidu():

global url

time_start = time.time()

r = requests.get(url=url)

times = time.time()-time_start

sys.stdout.write('status:%s time:%s current_time:%s\n'%(r.status_code,times,time.strftime('%H:%M:%S')))

def main():

threads = []

thread_count = 10

for i in range(thread_count):

t = threading.Thread(target=get_baidu,args=())

threads.append(t)

for i in range(thread_count):

threads[i].start()

for i in range(thread_count):

threads[i].join()

if __name__=='__main__':

爬虫中手动输入验证码方法无法获取图片src地址

验证码在html中图片标签内容:

<class=“verCodeImg” src="/kaptcha.jpg?v=0.234724039578059" οnclick=“verCode(this)”>

<class=“verCodeImg” src="/kaptcha.jpg?v=0.234724239578059" οnclick=“verCode(this)”>

可知获取到验证码的src地址就能动态的获得验证码

因为验证码是动态的!动态的!动态的!

用动态爬取网页的方法:

要用到selenium库

其实获得了验证码的src地址,我还是没能成功登陆

因为即使是相同的链接点进去,每一次刷新都会有不同的验证码

通过动态网页打开是一张

解析src地址出来是另一张

# coding:utf8

import urllib.request

import os

def download_img(img_url):

request = urllib.request.Request(img_url)

try:

response = urllib.request.urlopen(request)

img_name = img_url.split('/')[-1]

print(img_name)

filename = os.getcwd() + '/' + img_name

print(filename)

code = response.getcode()

print(code)

if (code == 200):

with open(filename, 'wb') as f:

f.write(response.read()) # 将内容写入图片

return filename

except:

return "failed"

if __name__ == '__main__':

# 下载要的图片

img_url = ''

print (download_img(img_url)+' download successfully!')