Article Directory
- 1. Preface
- 2. Libraries that need to be imported
- 3. Implementation process
- 1. Download link analysis
- 2. Code analysis
- 3 , Complete code
- 4. Blogger's speech
(Free learning recommendation: python video tutorial)
1. Preface
I crawled a lot of static before The content of web pages includes: novels, pictures, etc. Today I will try to crawl dynamic web pages. As we all know, Baidu Pictures is a dynamic web page. Then, rush! rush! ! rush! ! !
2. Libraries that need to be imported
import requestsimport jsonimport os
3. Implementation process
1. Download link analysis
First, open Baidu and search for a content. The search here is for the male god (himself)——Peng Yuyan
Then, open the packet capture tool , select the XHR option, press Ctrl R, and then you will find that as your mouse slides, one data packet after another will appear on the right.
(There is not too much sliding here. At first, the GIF recorded was over 5M because of too much sliding.)
Then, select a package and view it headers, as shown in the figure:
After intercepting, paste it on Notepad as a URL, which will be used later.
There are many, many parameters here, and I don’t know which ones can be ignored. I will simply copy them all in the following article. See the following article for details.
Here, the content that can be directly observed is over. Next, with the help of code, help us open the door to another world
That’s it!
2. Code analysis
First: Group the "other parameters" mentioned above together.
If you do it yourself, it is best to copy your own "Other parameters".
After that, we can try to extract it first, and change the encoding format to 'utf-8'
url = 'https://image.baidu.com/search/acjson?' param = { 'tn': 'resultjson_com', 'logid': ' 7517080705015306512', 'ipn': 'rj', 'ct': '201326592', 'is': '', 'fp': 'result', 'queryWord': '彭于晏', 'cl': '2', 'lm': '-1', 'ie': 'utf-8', 'oe': 'utf-8', 'adpicid': '', 'st': '', 'z': '', 'ic': '', 'hd': '', 'latest': '', 'copyright': '', 'word': '彭于晏', 's': '', 'se': '', 'tab': '', 'width': '', 'height': '', 'face': '', 'istype': '', 'qc': '', 'nc': '1', 'fr': '', 'expermode': '', 'force': '', 'cg': 'star', 'pn': '30', 'rn': '30', 'gsm': '1e', } # 将编码形式转换为utf-8 response = requests.get(url=url, headers=header, params=param) response.encoding = 'utf-8' response = response.text print(response)
The running results are as follows:
It looks quite messy. It’s okay. Let’s pack it up!
Add on the basis of the above:
# 把字符串转换成json数据 data_s = json.loads(response) print(data_s)
The running results are as follows:
Compared with the above, it is much clearer, but it is still not clear enough. Why Woolen cloth? Because its printed format is not convenient for us to view!
There are two solutions to this.
①Import the pprint
library, then enter pprint.pprint(data_s)
, and you can print, as shown below
②Use the json online parser (by Baidu), the results are as follows:
After solving the previous step, we will find that the data we want is all in data
Inside!
Then extract it!
a = data_s["data"] for i in range(len(a)-1): # -1是为了去掉上面那个空数据 data = a[i].get("thumbURL", "not exist") print(data)
The results are as follows:
At this point, 90% of the success has been achieved. All that remains is to save and optimize the code!
3. Complete code
This part is slightly different from the above. If you look carefully, you will find it!
# -*- coding: UTF-8 -*-""" @Author :远方的星 @Time : 2021/2/27 17:49 @CSDN :https://blog.csdn.net/qq_44921056 @腾讯云 : https://cloud.tencent.com/developer/user/8320044 """import requestsimport jsonimport osimport pprint# 创建一个文件夹path = 'D:/百度图片'if not os.path.exists(path): os.mkdir(path)# 导入一个请求头header = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}# 用户(自己)输入信息指令keyword = input('请输入你想下载的内容:')page = input('请输入你想爬取的页数:')page = int(page) + 1n = 0pn = 1# pn代表从第几张图片开始获取,百度图片下滑时默认一次性显示30张for m in range(1, page): url = 'https://image.baidu.com/search/acjson?' param = { 'tn': 'resultjson_com', 'logid': ' 7517080705015306512', 'ipn': 'rj', 'ct': '201326592', 'is': '', 'fp': 'result', 'queryWord': keyword, 'cl': '2', 'lm': '-1', 'ie': 'utf-8', 'oe': 'utf-8', 'adpicid': '', 'st': '', 'z': '', 'ic': '', 'hd': '', 'latest': '', 'copyright': '', 'word': keyword, 's': '', 'se': '', 'tab': '', 'width': '', 'height': '', 'face': '', 'istype': '', 'qc': '', 'nc': '1', 'fr': '', 'expermode': '', 'force': '', 'cg': 'star', 'pn': pn, 'rn': '30', 'gsm': '1e', } # 定义一个空列表,用于存放图片的URL image_url = list() # 将编码形式转换为utf-8 response = requests.get(url=url, headers=header, params=param) response.encoding = 'utf-8' response = response.text # 把字符串转换成json数据 data_s = json.loads(response) a = data_s["data"] # 提取data里的数据 for i in range(len(a)-1): # 去掉最后一个空数据 data = a[i].get("thumbURL", "not exist") # 防止报错key error image_url.append(data) for image_src in image_url: image_data = requests.get(url=image_src, headers=header).content # 提取图片内容数据 image_name = '{}'.format(n+1) + '.jpg' # 图片名 image_path = path + '/' + image_name # 图片保存路径 with open(image_path, 'wb') as f: # 保存数据 f.write(image_data) print(image_name, '下载成功啦!!!') f.close() n += 1 pn += 29
The running results are as follows:
Friendly reminder:
①: One page is 30 pictures
②: The input content can be varied: such as bridge, moon, sun, Hu Ge, Zhao Liying, etc.
4. Blogger’s speech
I hope you can like, follow, collect, and support it three times in a row!
A large number of free learning recommendations, please visit python tutorial(Video)
The above is the detailed content of python crawler: crawl Baidu pictures as you like. For more information, please follow other related articles on the PHP Chinese website!

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
