以下哪一项不是无限循环语句?
A.
while True:
print("hello")
B.
while "123"==123:
print("hello")
C.
while "abc">"ABC":
print("hello")
D.
while 1<2:
print("hello")
B. while "123"==123:
print("hello")
这不是一个无限循环语句,因为条件 "123"==123 是错误的。在Python中,字符串和整数是不同的数据类型,它们不相等,因此条件始终为 False。因此,该循环将无法执行。
网络爬虫抓取过程可以理解为模拟浏览器操作的过程,所以深入理解 HTTP 协议更有利于爬虫的学习,并且该部分是面试官非常喜欢问的部分,很重要,详情请见:https://blog.csdn.net/qq_21156327/article/details/105466469
import os
import re
import requests
from colorama import Fore
def download_image(url, keyword):
"""
下载图片
:param url: 百度图片的网址
:return: Bool
"""
# 1. 向服务器发起HTTP请求
response = requests.get(url)
# 2. 获取服务器端的响应信息
# 响应信息: status_code, text, url
data = response.text
# 3. 编写正则表达式,获取图片的网址
# "ObjURL":"http:\/\/img2.imgtn.bdimg.com\/it\/u=3459137507,1368309920&fm=214&gp=0.jpg"
# 获取到的: http:\/\/img2.imgtn.bdimg.com\/it\/u=3459137507,1368309920&fm=214&gp=0.jpg
# 正则的语法: .代表除了\n之外的任意字符, *代表前一个字符出现0次或者无数次. ?非贪婪模式
pattern = r'"ObjURL":"(.*?)"'
# 4. 根据正则表达式寻找符合条件的图片网址.
image_urls = re.findall(pattern, data)
# 5. 下载猫的图片到本地
index = 1
for image_url in image_urls:
# 转义字符: \n, \t, \ , \\,
image_url = image_url.replace('\\', '')
print(image_url) # 'xxxx.jpg xxxx.png'
# response.text返回unicode的文本信息, response.text返回bytes类型的信息
try:
response = requests.get(image_url)
except Exception as e:
print(Fore.RED + "[-]下载失败: %s" % (image_url))
else:
old_image_filename = image_url.split('/')[-1]
if old_image_filename:
image_format = old_image_filename.split('.')[-1]
# jpeg?imageview&thumbnail=550x0
if '?' in image_format:
image_format = image_format.split('?')[0]
else:
image_format = 'jpg'
# 生成图片的存储目录, keyword='cat', 'dog', 'python django'
keyword = keyword.replace(' ', '_')
print(keyword)
if not os.path.exists(keyword):
os.mkdir(keyword)
image_filename = os.path.join(keyword, str(index) + '.' + image_format)
with open(image_filename, 'wb') as f:
f.write(response.content)
print(Fore.BLUE + "[+] 保存图片%s.jpg成功" % (index))
index += 1
if __name__ == '__main__':
keyword = input("请输入批量下载图片的关键字: ")
# url地址里面参数信息可以长可以短, 有的参数可以省略的。
url = 'http://image.baidu.com/search/index?tn=baiduimage&word=' + keyword
print(Fore.BLUE + '[+] 正在请求网址: %s' % (url))
download_image(url, keyword)