How to use Scrapy to crawl Zhihu data?
Scrapy is a Python web crawler tool that can easily help us obtain various data on the Internet. Zhihu is a popular social question and answer platform. Use Scrapy to quickly capture questions, answers, user information and other data on Zhihu. This article will introduce how to use Scrapy to crawl Zhihu data.
- Installing Scrapy
First you need to install Scrapy. You can use the pip command to install it directly:
pip install scrapy
- Create Scrapy project
Enter the directory where you want to create a Scrapy project in the terminal and use the following command to create the project:
scrapy startproject zhihu
This command will create a Scrapy project named "zhihu" in the current directory.
- Create Spider
Use the following command to create a Spider file named "zhihu_spider.py" in the project directory:
scrapy genspider zhihu_spider zhihu.com
This command will Create a "zhihu_spider.py" file in the "spiders" subdirectory under the project directory. This file contains a Spider with zhihu.com as the starting URL.
- Write Spider code
Open the "zhihu_spider.py" file and add the following code:
import scrapy class ZhihuSpider(scrapy.Spider): name = 'zhihu' allowed_domains = ['zhihu.com'] start_urls = ['https://www.zhihu.com/'] def parse(self, response): pass
The code defines a file named "ZhihuSpider" Spider class. The Spider class needs to define the following attributes:
- name: Spider name
- allowed_domains: Accessed domain name
- start_urls: Spider’s starting URL
In this example, Spider's starting URL is set to zhihu.com. Spider must also contain a method called "parse" for processing the data returned by the response. In this example, the "parse" method is not implemented yet, so an empty "pass" statement is added first.
- Parse page data
After completing the Spider creation, you need to add the code to parse the page data. In the "parse" method, use the following code:
def parse(self, response): questions = response.css('div[data-type="question"]') for question in questions: yield { 'question': question.css('h2 a::text').get(), 'link': question.css('h2 a::attr(href)').get(), 'answers': question.css('div.zm-item-answer::text').getall(), }
This code gets the div element in the page that contains the "data-type" attribute without "question". Then, loop through each div element to extract the question title, link, and answer list.
In the above code, "yield" is a keyword in the Python language, used to generate a generator. A generator is an iterator containing elements. After each element is returned, execution is paused at the position of that element. In Scrapy, the "yield" keyword is used to return data parsed from the page into Scrapy.
- Run the crawler
After you finish writing the code, use the following command to run the crawler in the terminal:
scrapy crawl zhihu
This command will start the Scrapy framework and start Crawling Zhihu data. Scrapy will automatically access the starting URL specified in Spider and parse the returned page data through the "parse" method. The parsed data will be output to the terminal. If you need to save data, you can store the data in CSV, JSON, etc. files.
- Crawling user data
The above code can only crawl data such as questions and answers, but cannot obtain user information. If you need to crawl user data, you need to use Zhihu’s API interface. In Spider, you can use the following code to obtain the JSON format data returned by the API interface:
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} url = f'https://www.zhihu.com/api/v4/members/{user}?include=following_count,follower_count,badge[?(type=best_answerer)].topics&limit=20' yield scrapy.Request(url, headers=headers, callback=self.parse_user)
This code obtains the specified user information from the API interface. Here, the f-string formatted string is used to insert the username of the user to be obtained into the URL.
In the callback function, use the following code to extract the required data from the JSON format data:
def parse_user(self, response): data = json.loads(response.body)['data'] following_count = data['following_count'] follower_count = data['follower_count'] best_answerer = data['badge'][0]['topics'] yield { 'user_id': data['id'], 'name': data['name'], 'headline': data['headline'], 'following_count': following_count, 'follower_count': follower_count, 'best_answerer': best_answerer, }
This code extracts the user ID, user nickname, avatar, and follow from the JSON data Number, number of fans, best answer questions and other data.
- Summary
This article introduces how to use Scrapy to crawl Zhihu data. First, you need to create a Scrapy project and create a Spider. Then, use CSS selectors to parse the data in the page and store the crawled data in the generator. Finally, store it in CSV, JSON, etc. files, or output it directly to the terminal. If you need to obtain user data, you can use the Zhihu API interface to extract relevant data from JSON data.
The above is the detailed content of How to use Scrapy to crawl Zhihu data?. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to cancel the automatic renewal of Zhihu app membership? Zhihu app is a very practical mobile software. This software has many functions, and each function will bring a different feeling to the users. There are some contents on this software that require users to register as a member before they can read them. Membership on this software is not expensive, and continuous monthly membership will be cheaper. Some players want to know how to cancel automatic renewal. The editor below has compiled methods for canceling automatic renewal for your reference. How to cancel automatic renewal for Zhihu app members Zhihu members can choose four renewal methods, including Apple Pay, WeChat Pay, Alipay Pay and Baidu Pay. For users who choose Baidu Pay, renewal can be managed through WeChat or Alipay payment.

According to our understanding, the blacklisted person cannot directly know that he or she has been blacklisted. But if the blocked person sends a private message, they will realize they have been blocked by receiving a message that the message cannot be sent. However, if the person being blocked doesn't use private messaging, they may not be informed that they've been blocked.

1. Open the Zhihu app, click My in the lower right corner, and click the creation option. 2. On the Creation Center page, click My Content and click Articles. 3. After entering the article page, click Write Article below, edit the article content and publish it.

The personal homepage link in Zhihu can be copied, so how to copy the personal homepage link? Users need to go to their personal homepage, then click on the three dots on the upper right and choose to copy the link. This introduction to how to copy a personal homepage link can tell you the specific content. The following is a detailed introduction, so take a look! Zhihu tutorial: How to copy a link to Zhihu’s personal homepage? Answer: Click the three dots on your personal homepage and select Copy Link. Specific method: 1. First, click on the avatar in My to enter the homepage. 2. Click the three dots icon in the upper right corner. 3. Click the copy link below. Then you can send it to others

1. Open the Zhihu APP and click [My] in the lower right corner; 2. You can see [Night Mode] on the My interface, click to set it. If you have any questions, go to Zhihu. Zhihu, a trustworthy Q&A community, has the mission of allowing everyone to obtain trustworthy answers efficiently. Zhihu relies on its serious, professional and friendly community atmosphere, structured, easy-to-access high-quality content, and Q&A-based content production platform.

Open the Zhihu App, enter your personal homepage and click "Settings" → "Account and Security" → "VIP Membership Service" → "Purchase Membership Cycle" → "Cancel Automatic Renewal" to turn off the automatic renewal function to avoid unnecessary Deduction.

Regarding this platform, we have a lot of comments and other content that our friends are looking for, so no matter where we are, we can obtain and watch it through this platform. For viewing some of our own I believe that many users will be very interested in and like some of the comments. No matter what aspect it is, we can choose from various methods at any time, not only without restrictions, It also allows you to freely view some records of historical evaluations. It can be said to be very simple, but there are still a lot of users who don’t know how to perform these operations, so today I would like to wish you a happy new year. Let me give you a good explanation of some of the above choices. This is not to be missed. Hurry up and join us.

1. Open the Zhihu app. 2. Enter a question and click to write an answer. 3. Click on the video answer. 4. Click to add video to shoot.
