Multi-platform-oriented directional data acquisition method and system
Through the URL extraction algorithm based on tag attributes and text features and the automated crawling strategy of configuration templates, combined with the distributed crawling framework, the problem of low multi-platform data collection efficiency in public opinion data collection is solved, and efficient data collection and writing are achieved. Reduced crawler costs.
Patent Information
- Application Number
- CN202410162940.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-02-05
- Publication Date
- 2024-09-06
AI Technical Summary
Existing public opinion data collection methods are time-consuming and labor-intensive, difficult to process dynamic pages and multi-platform data, and writing crawler programs is costly and inefficient.
The URL extraction algorithm based on tag attributes and text features is used, combined with the automated crawling strategy of configured templates and the distributed crawling framework, to automatically crawl data from multiple platforms, reduce the cost of writing crawlers, and improve collection efficiency.
It achieves efficient data collection across multiple platforms, reduces the cost of writing crawlers, solves the problems of dynamic pages and in-depth crawling, and significantly improves collection efficiency.
Smart Images

Figure CN118606533A
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of public opinion data collection, and in particular to a multi-platform directional data collection method and system. Background Art
[0002] Public opinion data collection refers to the collection, organization and analysis of public opinion information through various channels, so as to obtain data such as the influence, attention and evaluation of a topic, event or person in society. With the rise of social media, public opinion data collection has become an important social research method and is widely used in government, business, media and other fields.
[0003] The public's demand for information is increasing. With the development and popularization of the Internet, the way the public obtains information has changed dramatically. Traditional media can no longer meet the public's demand for information, and online media platforms have become the main channel for the public to obtain information. Through the collection and analysis of public opinion data, we can better understand the public's views and attitudes on a topic or event. In the past, public opinion data collection mainly relied on manual collection and analysis, which was time-consuming and labor-intensive and prone to subjective bias. With the continuous development of computer technology and artificial intelligence technology, automated public opinion data collection methods have gradually been developed and applied, greatly improving the efficiency and accuracy of data collection. At the same time, public opinion data collection also faces a series of challenges and problems. For example, the data permissions and usage rules of web platforms are constantly changing, making it difficult to ensure the availability and credibility of data. In addition, how to extract valuable information from a large amount of data and how to accurately judge the public's emotions and attitudes are also important issues in the current research on public opinion data collection. Therefore, the research on public opinion data collection is of great significance. Through the research on public opinion data collection methods, technologies and tools, the efficiency and accuracy of data collection can be continuously improved to better serve social surveys and public opinion analysis. At the same time, research on the difficulties and problems in collecting public opinion data can provide theoretical and technical support for solving practical problems.
[0004] Through in-depth research on the collection and analysis of public opinion data, it is expected to provide more scientific and comprehensive information support for public opinion management, policy making, social research and other fields. Therefore, this study aims to use advanced crawler technology to collect public opinion data such as current political hot spots from domestic mainstream news websites and social media platforms, so as to analyze social dynamics more comprehensively and deeply, provide more accurate reference for government decision-making and public opinion management, reveal the potential laws in the information network, and provide strong support for us to better understand social public opinion and respond to social changes.
[0005] Currently, data collection is generally carried out by writing web crawlers, which usually include the following steps: determining the target website, extracting page URLs, processing and parsing pages, extracting HTML document text, data processing, data storage, etc. When collecting web page data, it is necessary to ensure compliance with relevant laws and the website's terms of use, respect the website's privacy policy, and ensure that data collection will not cause network attacks on the website. In addition, in order to ensure the comprehensiveness and diversity of public opinion data, it is often necessary to collect data from multiple web platforms. However, the current public opinion data collection has the following problems that need to be solved:
[0006] First, in terms of URL extraction, the traditional approach is to mark the module where the URL tag is located through manual annotation according to the different target websites. This method is time-consuming and requires a lot of manpower; in the process of crawling multiple platforms, the traditional approach requires writing a separate crawler program for each page, which is time-consuming and labor-intensive, and it is difficult to handle dynamic pages; in addition, the traditional single crawler collection is very slow when faced with many web pages and large amounts of data, and it is difficult to coordinate the collection process between multiple websites. Summary of the invention
[0007] The purpose of the present invention is to provide a multi-platform directional data collection method and system, which replaces the manual annotation method to locate and extract URLs, is applicable to multiple platforms, reduces the cost of writing crawlers, solves the problems of dynamic pages and deep crawling through automated crawling, and improves efficiency when crawling data from multiple platforms at the same time.
[0008] To achieve the above object, the present invention provides the following solutions:
[0009] A multi-platform directional data collection method, comprising:
[0010] Identify target websites;
[0011] Determine the location of the URL to be crawled on the page of the target website;
[0012] Extract the URL of the page to be crawled, and add the extracted URL to the queue to be crawled;
[0013] Access the page corresponding to the URL and obtain the HTML document of the page;
[0014] The HTML document is processed and parsed to obtain target data.
[0015] Optionally, the multi-platform directional data collection method further includes:
[0016] The target data is preprocessed.
[0017] Optionally, determining the position of the URL to be crawled on the page of the target website specifically includes the following steps:
[0018] Get all the pages Label; Tags indicate tags that can be jumped by clicking;
[0019] Regarding the Labels are preprocessed;
[0020] Calculate all preprocessed The attribute similarity between tags.
[0021] Calculate all The similarity of text features between tags.
[0022] Based on the attribute similarity and text feature similarity calculation The similarity between two labels;
[0023] Based on the The similarity between two labels determines the similarity matrix;
[0024] Cluster the label similarity matrix to obtain several The collection of tags is denoted as Cluster;
[0025] From the several Get the Cluster where the target tag is located from the tag collection;
[0026] Extract the URL based on the Cluster where the target tag is located.
[0027] Optionally, calculate all preprocessed The attribute similarity between tags is calculated using the following formula:
[0028]
[0029] Among them, x and y represent the n-dimensional similarity vectors of two labels, ||x|| and ||y|| represent the L2 norm of x and y, respectively. i Represents the value of the i-th dimension of vector x, y i Represents the value of the i-th dimension of vector y.
[0030] Calculate all The similarity of text features between tags is calculated using the following formula:
[0031]
[0032] Among them, x represents, y represents, Len(x text ) indicates that Len(y text ) means that Dep(x text ) means that Dep(y text )express.
[0033] Optionally, based on the attribute similarity and text feature similarity calculation The similarity between two labels is calculated using the following formula:
[0034] Similarity(x,y)=α×Similarity tfidf (x,y)+β×Similarity text (x,y)
[0035] Among them, Similarity(x,y) represents the overall similarity of labels x and y. tfidf (x,y) represents the label attribute similarity of labels x and y. text (x,y) represents the text feature similarity of labels x and y, and α represents Similarity tfidf The weight coefficient of (x, y) is 0.4, and β represents Similarity text The weight coefficient of (x,y) is 0.6.
[0036] Optionally, extracting the URL of the page to be crawled and adding the extracted URL to the queue to be crawled specifically includes the following steps:
[0037] WebDriver: Load the configuration template, open the Chrome Webkit kernel, start the WebDriver engine, and set the initial URL of the webpage, the domain name allow_domain allowed to be crawled, and the domain name deny_domain denied to be crawled; the configuration template includes: template configuration module, collection rule module, exception handling module, error warning module, URL extraction module, page turning rule module, detailed information extraction module and anti-crawling module;
[0038] Loading template rules: loading the configured template, which includes all modules except the anti-crawling module;
[0039] Crawl the target website: start the crawler, start crawling according to the template loading rules, extract the URL of the detail page on the target website, and add it to the URL queue;
[0040] Extracting details page data: taking out the URL from the URL queue according to the scheduling rules, accessing its corresponding details page, extracting details page data and saving it;
[0041] Page turning: The crawling of the current page is completed. If there is a next page, continue to crawl the next page according to the page turning rule module, otherwise close the crawler.
[0042] End: Crawler execution stops, log printing stops, and WebDriver is closed.
[0043] Optionally, between step "WebDriver" and step "adding disguise information" further includes:
[0044] Add camouflage information: load the anti-crawl module.
[0045] Optionally, accessing the page corresponding to the URL and obtaining the HTML document of the page specifically includes the following steps:
[0046] Configure master nodes and slave nodes: each web page is assigned a master node, and slave nodes are set according to the web page estimate;
[0047] Redis initialization: According to the configured master node, a Redis message queue is allocated to each web page to store the URL extracted from the web page, ensuring that all slave nodes corresponding to the master node share the URL queue;
[0048] Data crawling: including WebDriver initialization, loading configuration templates, URL extraction, and detail page data extraction;
[0049] End: After the crawl is completed, save the Redis log, clear the cache, and close the master node and slave node.
[0050] Optionally, processing and parsing the HTML document to obtain target data specifically includes the following steps:
[0051] HTML document parsing: Get the Response object returned by the downloader, which includes the HTML file of the current page and the response status code;
[0052] Determine whether the response code is 200. If it is not 200, it means the crawling has failed and the process is transferred to the exception handling module. If it is 200, it means the crawling has succeeded. The HTML string is taken from the Response object and parsed based on BeautifulSoup to obtain the parsed data.
[0053] Dom tree construction: After parsing with BeautifulSoup, the HTML string is obtained, and the carriage return, line feed, tab, special expressions and special characters are removed. The Dom tree is generated by parsing with HTMLResponse, and the element positioning method is adopted according to the page structure, and the methods of start_with() and contain()Response objects are used to locate the position of the field to be extracted; the element positioning method includes: id selector, class selector and tag selector;
[0054] Data extraction: According to the location of the field to be extracted, based on the string() and extract_first() methods, extract the data corresponding to the field;
[0055] Storage and downloading: The extracted fields are stored in the Items object and handed over to the pipeline, which triggers the pipeline method to store and download data.
[0056] Based on the above method in the present invention, the present invention further provides a multi-platform directional data collection system, comprising:
[0057] A target website determination module, used to determine the target website;
[0058] A module for determining the position of the URL to be crawled on the page, used to determine the position of the URL to be crawled on the page in the target website;
[0059] The URL extraction module of the page to be crawled is used to extract the URL of the page to be crawled and add the extracted URL to the queue to be crawled;
[0060] The HTML document acquisition module of the page is used to access the page corresponding to the URL and obtain the HTML document of the page;
[0061] The processing and parsing module is used to process and parse the HTML document to obtain target data.
[0062] According to the specific embodiments provided by the present invention, the present invention discloses the following technical effects:
[0063] The present invention proposes a URL extraction algorithm based on tag attributes and text features, which can locate and extract URLs instead of manual annotation, and is applicable to multiple platforms. In the process of crawling multiple platforms, the present invention proposes an automated crawling strategy based on configuration templates, extracts the common logic of URL extraction of multiple platforms and encapsulates it as a module, which greatly reduces the cost of writing crawlers, and solves the problems of dynamic pages and deep crawling through automated crawling. In terms of acquisition efficiency, the present invention rewrites the core module of the Scrapy crawler framework, and adds a distributed scheduling strategy and node middleware to build a distributed crawling framework, which significantly improves the efficiency when crawling data from multiple platforms at the same time. BRIEF DESCRIPTION OF THE DRAWINGS
[0064] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the drawings required for use in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative labor.
[0065] Figure 1 A flow chart of a multi-platform directional data collection method provided by the present invention;
[0066] Figure 2 An example diagram of a web page URL tag module provided by the present invention;
[0067] Figure 3 The label attributes and text description diagram provided by the present invention;
[0068] Figure 4 A flowchart of the URL extraction algorithm based on tag multi-features and text density similarity provided by the present invention;
[0069] Figure 5 A flow chart of the automatic extraction strategy based on the configuration template provided by the present invention;
[0070] Figure 6 The Scrapy crawling flow chart provided by the present invention;
[0071] Figure 7 The distributed crawling structure diagram provided by the present invention;
[0072] Figure 8 This is the HTML document Dom tree parsing structure diagram provided by the present invention. DETAILED DESCRIPTION
[0073] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0074] The purpose of the present invention is to provide a multi-platform directional data collection method and system, which replaces the manual annotation method to locate and extract URLs, is applicable to multiple platforms, reduces the cost of writing crawlers, solves the problems of dynamic pages and deep crawling through automated crawling, and improves efficiency when crawling data from multiple platforms at the same time.
[0075] In order to make the above-mentioned objects, features and advantages of the present invention more obvious and easy to understand, the present invention is further described in detail below with reference to the accompanying drawings and specific embodiments.
[0076] Embodiment 1
[0077] Figure 1 A flow chart of a multi-platform directional data collection method provided by the present invention, such as Figure 1 As shown, the method includes:
[0078] Step 1: Identify your target website.
[0079] In this embodiment, the target website can be any news website.
[0080] Step 2: Determine the location of the URL to be crawled on the page of the target website.
[0081] At present, most web pages comply with the HTML semantic standard, that is, "the tag name matches the content semantics", such as using the title tag ( <h1>~< / h1> <h6>) indicates the title, and a hyperlink tag ( ) indicates a URL that can be redirected by clicking on it, and uses a paragraph tag ( ) indicates a piece of text, etc. By observing the structures of several mainstream public opinion web pages, we found that they all comply with the above specifications. All URLs on the pages are located in In the href attribute of the tag, very few websites place the URL in 、 etc. tags, but most of their contents are useless URLs and have no extraction value, so the present invention only considers the standard situation.
[0082] On the page Tags can generally be divided into the following categories: Figure 2 An example is given: the URL to be extracted, that is, the blue box in the figure, can be jumped to the data details page after clicking. For the convenience of description, it is called the target URL. The label is called the target label; the navigation URL, which is the yellow box in the figure, is usually the navigation information at the top and end of the page, and is a noise label; the advertising URL, which is the green box in the figure, can be anywhere on the page, and is also a noise label. Therefore, the problem is transformed into a given Find the target tag in the tag group.
[0083] After fully comparing the attributes of different web pages, different modules, and different URL tags, we found that the tags where the page URLs are located often have the same structure, and the difference between these tags and other noise tags lies mainly in the attributes of the tags (such as class, id, href, etc.) and the text density (such as the length of the Chinese characters contained in the tags). Figure 3 As shown:
[0084] The basic idea of this step is to analyze all The characteristics of the tags are vectorized based on the tag attributes. The cosine similarity between the tags is calculated to form a similarity matrix. After clustering, the tag where the target URL is located is obtained.
[0085] The specific steps are as follows:
[0086] Step 2.1: Get all Tags. Parse the Dom structure of the HTML file based on BeautifulSoup to obtain all Label.
[0087] Step 2.2: Tag preprocessing. This mainly includes tag cleaning, word segmentation, and stop word removal. In the cleaning phase, irrelevant characters in the tag are filtered out, and the text content in the tag is removed to obtain a tag that only retains the tag attributes. Tag string; in the word segmentation stage, it is important to keep the word intact for each set of attribute key-value pairs. For example, "class = 'news-tag'" should be segmented into two words, "class" and "news-tag", rather than three words, "class", "news", and "tag". When removing stop words, common stop words are excluded to reduce noise.
[0088] Step 2.3: Calculate the similarity of label attributes. Mainly calculate all The attribute similarity between tags is calculated pairwise, and the tag string is vectorized based on the improved TF-IDF. First, the basic TF-IDF algorithm is introduced: the word frequency TF represents the frequency of occurrence of a specific word in the text, the inverse document word frequency IDF is used to measure the prevalence of the word, and the TF-IDF value is used to measure the importance of a word to a certain text.
[0089] tfidf i,j =t ij ×idf i
[0090] The TF value is usually obtained through the calculation of the bag-of-words model, and its calculation formula is as follows.
[0091]
[0092] In this formula, t ij represents the frequency of occurrence of word i in document j, n i,j represents the number of occurrences of word i in document j, ∑ k n k,j Represents the sum of the number of occurrences of all words in document j.
[0093]
[0094] In this formula, idf i represents the inverse document frequency of word i, |D| represents the total number of text sets, |D i | represents the total number of texts containing word i in the text set, and +1 is used to avoid the situation where the divisor is 0 due to word i not belonging to any text. Therefore, the final calculation formula of TF-IDF is as follows:
[0095]
[0096] However, TF-IDF only considers the word frequency and inverse document frequency of the feature words in the text, ignoring the characteristics of HTML tags. Different attributes of tags (such as class value, href value) have different influences on tags. The class values of the same type of tags are usually the same, but the href values are usually different. For example, for the following two The labels should belong to the same category through direct observation, but the values of the href attributes are different. This leads to the difference between the two labels becoming larger in the similarity calculation stage after the TF-IDF feature vector is constructed, which reduces the similarity and affects the subsequent clustering results.
[0097] " <a class=”news-tag”href=" c 8wzgbp7vatq"target=’_blank’rel> The peak travel period for May Day has arrived ”
[0098] " <a class=”news-tag”href=" c 6ausjp9guhsd"target=’_blank’rel> The popularity of barbecue in a certain area has decreased, and changes should continue to be sought ”
[0099] Therefore, we improve TF-IDF here and introduce a weight adjustment factor ω to weaken the above influence.
[0100]
[0101] In this formula, ∑ k ∑ j n k,j Indicates the total number of occurrences of all types of words in the text set, ∑ i n i,j Represents the total number of times word i appears in the text set
[0102] In order to reduce the difference between vectors, a normalization coefficient β is introduced.
[0103]
[0104] Among them, x represents the current sample data, min represents the minimum value of the sample data, and max represents the maximum value of the sample data.
[0105] The final improved TF-IDF calculation formula is shown below, and the TF-IDF vector matrix of the label is constructed based on the calculation results.
[0106]
[0107] Define the TF-IDF vector similarity of labels x and y as Similarity tfidf (x, y), the cosine distance is used to calculate the similarity. Assuming that the TF-IDF vectors x and y of x and y are both n-dimensional, the calculation formula is as follows:
[0108]
[0109] In this formula, ||x||, ||y|| represent the L2 norm of vectors x and y respectively.
[0110] Step 2.4: Calculate the similarity of text features. Mainly calculate all The similarity of text features between tags includes text length and text depth. By observing multiple web pages, we know that the text length in the target URL is relatively long, mostly between 10-25 words, while the text length of the noise URL is relatively short, mostly less than 10 words. In addition, the text in different tags is at different depths of the DOM layer. Therefore, the text features are jointly characterized by text length and text depth. Table 1 gives an example. For the convenience of representing text features, the tag attributes are omitted.
[0111] Table 1 Text feature instance table
[0112]
[0113] Define the text feature similarity of labels x and y as Similarity text (x,y), the calculation formula is as follows:
[0114]
[0115] Among them, Len(x text ) indicates the text length of label x, Len(y text ) represents the text length of label y, Dep(x text ) represents the text depth of label x, Dep(y text ) represents the text depth of label y.
[0116] Step 2.5: Label classification. First, we need to calculate the similarity between labels. We define the label similarity of labels x and y as Similarity(x,y). tfidf The result of (x,y) and Similarity in step 2.4 text (x, y) weighted calculation, the final calculation formula is as follows, where α is 0.4 and β is 0.6.
[0117] Similarity(x,y)
[0118] =α×Similarity tfidf (x,y)+β×Similarity text (x,y)
[0119] The n-dimensional similarity matrix M will be obtained through calculation with this formula.
[0120]
[0121] Where n is the total number of tags, w ij Indicates the similarity between label i and label j.
[0122] The label similarity matrix is then clustered. The KMeans algorithm is an iterative clustering algorithm whose goal is to divide the data set into k different groups so that each data point belongs to the group represented by the nearest mean (center). Specifically, the algorithm performs the following steps:
[0123]
[0124] After the previous step, we have obtained the similarity matrix, which is composed of n n-dimensional similarity vectors. Therefore, in the above formula 3, x i is the i-th similarity vector; c i For x i The cluster to which it belongs, is the center point of the cluster, and M is the total number of vectors. Repeat the above process until the cost function J converges. For each similarity vector x i , assign it to the nearest cluster center, for each cluster center k, recalculate the center of the class, and repeat the above steps until the cluster center no longer changes significantly or reaches the predetermined number of iterations. When the algorithm converges, each data point is assigned to a cluster center, forming k clusters.
[0125] Since KMeans is greatly affected by the selection of the initial center point, in actual operation, the improved KMeans solution KMeans++ is selected for clustering. A collection of tags, each of which is called a Cluster.
[0126] Step 2.6: Get the target class. From the several clusters obtained in the previous step, get the cluster where the target label is located and define the Average length (cluster i ) represents the average text length of the Cluster, and its calculation formula is as follows:
[0127]
[0128] in, It represents the sum of the text lengths in all clusters. Among the clusters obtained by clustering, the cluster with the largest average text length is selected, which is the cluster where the target URL is located.
[0129] Step 2.7: URL extraction. In the previous step, we have extracted a set of all target tags. Finally, we need to extract the URL from the tag. Here we use BeautifulSoup, which is a Python library that extracts data from HTML or XML files. We use it to get the target URL. All the attributes attrs of the tag are used to formulate corresponding regular expressions according to the attribute characteristics, and then the target URL is automatically extracted in conjunction with XPath.
[0130] Step 3: Extract the URL of the page to be crawled, and add the extracted URL to the queue to be crawled.
[0131] This step proposes an automated extraction strategy based on configuration templates:
[0132] Specifically, it is time-consuming and labor-intensive to write a crawler program for each web page separately, and when there are many pages to crawl, a large number of redundant modules need to be written, which reduces the development efficiency. In addition, a tricky difficulty is that with the development of Web2.0, most websites will use JavaScript and Ajax technology to create dynamic websites. Nowadays, dynamic web pages contain a huge amount of data. Many web pages adopt the dynamic web page mode, that is, the content of the HTML page is not completely returned by the interface, but is dynamically spliced on the page by JavaScript scripts. It is difficult to get the data in the web page directly from the interface, so the system needs to provide support for the collection of dynamic web pages. For the collection of dynamic pages, the page rendering engine is currently used to render the page. However, due to the uneven level of different website developers and the iterative update of website building technology, the page rendering engine is very likely to have problems such as incompatibility. Therefore, the system needs to provide a general solution to realize the collection of dynamic pages. In addition, when there are many web pages to crawl, a lot of manual configuration is required to adapt to different pages, which is inefficient and cannot achieve automatic crawling. Therefore, the present invention proposes a template extraction strategy based on configuration templates, which aims to configure a set of similar collection templates, extract the common logic of crawling multiple platforms and encapsulate them into modules, so that when crawling on multiple platforms, each platform only needs to make a small amount of changes to the common collection template to meet the crawling needs of the website, and builds a set of automated crawling frameworks to solve the problems existing in crawling dynamic pages, and has good anomaly detection and error reminders.
[0133] The configuration template part mainly includes: template configuration module, collection rule module, exception handling module, error alarm module, URL extraction module, page turning rule module, detail information extraction module, anti-crawling module, etc. The design and configuration of these modules are aimed at providing comprehensive and customizable functions for the entire crawler system to ensure that the system can respond flexibly and efficiently to different web page structures and data extraction requirements. At the same time, it can take into account exception handling, error prompts, anti-crawling response and other aspects during the crawling process. The specific functions of each module are as follows:
[0134] Template configuration module: mainly responsible for the basic configuration of crawling, including project name, crawler name, basic parameters of crawler, single node or distributed mode selection, whether to enable caching, whether to enable endpoint re-crawling, required middleware, required pipelines, database configuration, etc. After this step, the basic parameters required for the crawler will be configured.
[0135] Collection rule module: The purpose is to configure the module in detail, mainly including processing the domain names allowed to be crawled, setting the interval time between two crawls, setting collector rules, etc.
[0136] Exception handling module: The purpose is to configure the module in detail, including whether to enable exception handling, whether to record exception logs, set exception log format, null value processing rules, etc.
[0137] Error alarm module: The purpose is to configure the module in detail, including whether to enable the error pop-up alarm function, whether to enable the error re-climbing function, etc.
[0138] URL extraction module: mainly responsible for calling the URL extraction algorithm based on tag features and text density similarity, and adding the collected URLs to the collector's scheduling queue, waiting for subsequent crawling of HTML document data.
[0139] Page turning rule module: It is mainly responsible for automatically turning to the next page to continue crawling after the current page URL is extracted, so as to achieve in-depth crawling of web pages and ensure the integrity and comprehensiveness of the data.
[0140] Details information extraction module: mainly responsible for parsing the details page document corresponding to the URL and data extraction, including HTML page parsing, Dom data construction, selector rule setting, extraction field setting, whether to collect pictures, whether to collect videos, etc.
[0141] Anti-crawling module: Cookie pool and User-Agent pool are built. Websites that do not require login do not need to carry Cookie information, which is used as a backup. The User-Agent pool adopts two methods: manual random function and fake-useragent.
[0142] Once the configuration template is built, the difficulty of writing a crawler for a certain platform will be greatly reduced. You only need to specify the URL of the web page, the page turning method, the page body attribute identifier and other unique attributes of each web page, and introduce the above public template to quickly write a set of crawler programs, which improves the efficiency of writing crawler programs. In addition, this strategy builds an automated crawling framework and introduces the WebDriver automation engine. WebDriver can simulate user behavior in the browser, including clicking, scrolling, input, etc. This helps to bypass the anti-crawler mechanism of some websites because the crawler's behavior is closer to the real user and difficult to detect. The steps of the automated extraction strategy based on the configuration template are as follows, Figure 5 The flow chart is given, and the specific steps of the process are as follows:
[0143] Step 3.1: WebDriver: Load the configuration template, open the Chrome Webkit kernel, start the WebDriver engine, and set the initial URL of the web page, the domain name allowed to crawl allow_domain, and the domain name denied to crawl deny_domain.
[0144] Step 3.2: Load template rules: Load the configured template, which mainly includes all modules except the anti-crawl module.
[0145] Step 3.3: Add disguise information: This step is optional and will load the anti-crawling module. Since many websites do not have an anti-crawling mechanism and do not need to use dynamic cookie pools and other methods, this step is optional.
[0146] Step 3.4: Crawl the target website: Start the crawler, start crawling according to the above rules, extract the URL of the detail page on the target website, and add it to the URL queue.
[0147] Step 3.5: Extracting details page data: Take out the URL from the URL queue according to the scheduling rules, access its corresponding details page, extract the details page data and save it. The specific technology will be explained below.
[0148] Step 3.6: Page turning: The crawling of the current page is completed. If there is a next page, continue to crawl the next page according to the page turning rules, otherwise close the crawler.
[0149] Step 3.7: End: The crawler execution stops, log printing stops, and WebDriver is closed.
[0150] The environment configuration used in the above steps is shown in Table 2 below:
[0151] Table 2 Automatic extraction strategy environment configuration table based on configuration template
[0152]
[0153] Step 4: Access the page corresponding to the URL and obtain the HTML document of the page.
[0154] This step proposes a distributed scheduling strategy for multi-platform crawling.
[0155] When there are many web pages to crawl, traditional crawling solutions have some problems. In terms of performance, traditional crawlers usually run on a single machine. When a large number of requests need to be processed or large-scale data needs to be crawled, the stand-alone crawler may not be able to fully utilize the resources, resulting in a slower crawling speed. In terms of scalability, the scalability of stand-alone crawlers is limited, and the only option is to upgrade the hardware, but it will result in high cost-effectiveness. In terms of fault tolerance, when a stand-alone crawler faces problems such as network failures and program crashes, it may cause the crawler to be interrupted, the task fails and the task is terminated, and it is impossible to continue crawling from the last endpoint. In terms of large-scale crawling, stand-alone crawlers may not be able to effectively manage and schedule tasks. In terms of deduplication, in a stand-alone environment, deduplication is usually implemented using local memory or database, but this may cause inaccurate deduplication or performance problems in a distributed environment.
[0156] Therefore, the present invention first builds a basic crawler framework based on Scrapy, then rewrites some core modules in Scrapy, and introduces distributed scheduling strategies and node middleware to build a distributed crawler framework. Scrapy is an open source Python framework for crawling website data. By utilizing middleware, pipelines, and extensions, users can flexibly customize crawler behavior according to their needs; in addition, Scrapy provides a highly abstract interface that shields many underlying details, allowing users to focus on the implementation of crawler logic without having to pay too much attention to details such as network requests and data storage; finally, Scrapy has built-in powerful selectors (such as Xpath, CSS selectors, etc.), making the data extraction process more flexible and simple. This solution builds the Scrapy framework according to the following 6 steps, and the crawling flow chart of the framework is as follows Figure 6 As shown, specifically including:
[0157] Initialize the crawler engine: the core module, connecting other modules and the data collection process management platform.
[0158] Build middleware: rewrite middleware, load automated crawling strategies, and process requests and responses.
[0159] Build a scheduler: a container that stores and manages URLs, schedules, and dispatches tasks.
[0160] Build a downloader: send a request, pre-parse and store the Response object.
[0161] Build a crawler instance: parse the page according to the Response object and process the data extraction logic.
[0162] Build a pipeline: parse data, persist data, download data and write it to the database.
[0163] In order to adapt Redis to realize multi-platform distributed crawling, it is necessary to make a relatively large transformation of the Scrapy framework. The present invention rewrites several core modules of Scrapy, changes its scheduling mode from single-threaded scheduling to distributed scheduling, and rewrites its native scheduling queue to a priority scheduling queue based on Redis. The specific parts of the transformation are as follows:
[0164] Rewrite the scheduler: Rewrite the Scrapy Scheduler and change it to a redis-based priority queue scheduling to support multi-node concurrent crawling, and introduce the Bloom filter deduplication strategy to improve the deduplication speed when facing large amounts of data.
[0165] Rewrite the downloader: Rewrite the Scrapy Downloader to adapt to the automated Chrome Webkit kernel and WebDriver engine, be compatible with the entire process of automated crawling, and support dynamic downloading.
[0166] Rewrite middleware: Rewrite Scrapy Middlewares, add HTMLResponse and Redis adapter modules, and package the Response of each web page into the required format.
[0167] Rewrite pipelines: Rewrite Scrapy Pipelines, improve data processing logic, share downloaded data on multiple nodes, and support concurrent reading and writing of files and database writing.
[0168] Set up the master node: Each web page is assigned a master node, which is responsible for URL extraction and automatic control.
[0169] Set up slave nodes: Each master node is assigned a number of slave nodes according to the task scale, which are responsible for HTML document data extraction, data download, and writing to the database.
[0170] Since there are many experimental platforms, it is impossible to allocate an actual server to each platform to test the distributed scenario. Therefore, this experiment uses two servers to simulate distributed scheduling. Different master nodes are deployed on one server in the form of multiple processes, and the slave node groups corresponding to different masters are deployed on another server in the form of multiple processes. The environment configuration used by the distributed strategy is shown in Table 3 below:
[0171] Table 3 Distributed scheduling strategy environment configuration table
[0172] Environment Configuration Configuration Instructions Python 3.9 Scrapy 2.9.0 Scrapy Scheduler scrapy_redis.scheduler.Scheduler Redis Port redis: / / xxx.xxx.xxx.xxx:6379 Redis Duplicator Bloom filter Redis Scheduler scrapy_redis.queue.SpiderPriorityQueue server CentOS Linux release 7.3.1611(Core) database MySQL 5.6.24
[0173] The working process of the modified distributed crawler is as follows:
[0174] Step 4.1: Configure the master node and slave nodes. Assign a master node to each web page and set the slave nodes according to the web page estimate. If the HTML structure is not complex and the data volume is small, set 2 to 3 slave nodes. If the HTML structure is complex and the data volume is large, set 3 to 5 slave nodes.
[0175] Step 4.2: Redis initialization: According to the master node configured in the previous step, a Redis message queue is allocated to each web page to store the URL extracted from the web page, to ensure that all slave nodes corresponding to the master node share the URL queue.
[0176] Step 4.3: Data crawling: This step is the same as the previous step. Figure 5 The steps are basically the same, mainly including WebDriver initialization, loading configuration templates, URL extraction, detail page data extraction, etc., which will not be repeated here. There are two key differences: The first difference is, Figure 5 The steps are a single-node crawling process, in which URL extraction and detail page data extraction share the same process. In this step, the URL data is only managed by the master node, and the detail page data extraction is distributed to all slave nodes, and no longer shares a process. The second difference is that due to the limitation of single-node shared processes, URL extraction uses Scrapy's own URL queue, and because the speed of detail page data extraction is much slower than that of URL data extraction, the overall crawling speed is limited. In this step, Redis's URL queue is used, and the process is no longer shared, which greatly speeds up the crawling speed.
[0177] Step 4.4: End: After the crawl is completed, save the Redis log, clear the cache, and close the master node and slave node.
[0178] The structure of the modified distributed crawling framework is as follows Figure 7 As shown in the figure, each web page will be divided into a separate master node in batches, and its unique master_key will be maintained as an identifier. The master node will then load and execute the automated collection process mentioned in the previous section to extract URLs and push the extracted URLs to the Redis queue. After a series of middleware processing, the tasks corresponding to different master_keys will be dispatched to different Scrapy instances. Each Scrapy instance will be assigned several slave nodes, which will take out the URLs in turn to extract data from HTML documents, and finally download and save the extracted data to the database.
[0179] Step 5: Process and parse the HTML document to obtain target data.
[0180] After the URL collection is completed, the next step is to parse the HTML document. The specific method is to access each URL, obtain its corresponding HTML document and extract data. In this process, you first need to parse and build the DOM tree based on the HTML document, find the parsing node based on the DOM tree and attribute name, then remove the useless tags on the DOM tree, and finally format it to obtain a pure tree data structure. The specific execution steps are as follows:
[0181] Step 5.1: HTML document parsing: Get the Response object returned by the downloader, which contains the HTML file of the current page and the response status code. First, determine whether the response code is 200. If it is not 200, it means the crawling failed, and transfer to the exception handling module; if it is 200, it means the crawling is successful, take out the HTML string from the Response object, and parse it based on BeautifulSoup to get the parsed data.
[0182] Step 5.2: Dom tree construction: After parsing with BeautifulSoup, we can get the HTML string. Remove the carriage return, line feed, tab, special expressions, special characters, etc., parse it through HTMLResponse and generate a Dom tree. According to the page structure, a series of element positioning methods are adopted, such as id selector, class selector, tag selector, etc., and the methods of the Response object such as start_with() and contain() are used to locate the location of the field to be extracted.
[0183] Step 5.3: Data extraction: Perform this operation for each field, and extract the data corresponding to the field based on the corresponding position of the field based on methods such as string() and extract_first().
[0184] The field content includes title, body, description, release time, keywords, details page ID, details page URL, source website, author, editor, editing date, number of readings, number of comments, and number of likes, etc. You can select the collected content according to actual needs.
[0185] Step 5.4: Storage and Download: Store the extracted fields in the Items object and pass it to the pipeline, which triggers the pipeline method to store and download the data.
[0186] The Dom tree generated after HTML parsing is as follows Figure 8 shown.
[0187] Based on the above strategies, the efficiency of writing crawlers when crawling on multiple platforms is greatly improved. Depending on the platform, only a small amount of changes need to be made to the template, such as page turning rules, detailed information extraction, etc., which have good versatility when crawling between different platforms. The automated construction process reduces the time of manual operation and controls the entire URL extraction process by WebDriver.
[0188] Embodiment 2
[0189] In order to execute the method corresponding to the above embodiment 1 to achieve corresponding functions and technical effects, a multi-platform directional data collection system is provided below, including:
[0190] A target website determination module, used to determine the target website;
[0191] A module for determining the position of the URL to be crawled on the page, used to determine the position of the URL to be crawled on the page in the target website;
[0192] The URL extraction module of the page to be crawled is used to extract the URL of the page to be crawled and add the extracted URL to the queue to be crawled;
[0193] The HTML document acquisition module of the page is used to access the page corresponding to the URL and obtain the HTML document of the page;
[0194] The processing and parsing module is used to process and parse the HTML document to obtain target data.
[0195] In this specification, each embodiment is described in a progressive manner, and each embodiment focuses on the differences from other embodiments. The same or similar parts between the embodiments can be referred to each other. For the system disclosed in the embodiment, since it corresponds to the method disclosed in the embodiment, the description is relatively simple, and the relevant parts can be referred to the method part.
[0196] The principles and implementation methods of the present invention are described in this article using specific examples. The description of the above embodiments is only used to help understand the method and core idea of the present invention. At the same time, for those skilled in the art, according to the idea of the present invention, there will be changes in the specific implementation methods and application scope. In summary, the content of this specification should not be understood as limiting the present invention. < / h6>
Claims
1. A multi-platform directional data collection method, characterized in that: include: Identify target websites; Determine the location of the URL to be crawled on the page of the target website; Extract the URL of the page to be crawled, and add the extracted URL to the queue to be crawled; Access the page corresponding to the URL and obtain the HTML document of the page; The HTML document is processed and parsed to obtain target data.
2. The multi-platform directional data collection method according to claim 1, characterized in that: The multi-platform directional data collection method further includes: The target data is preprocessed.
3. The multi-platform directional data collection method according to claim 1, characterized in that: Determining the location of the URL to be crawled on the page of the target website specifically includes the following steps: Get all the pages Label; Tags indicate tags that can be jumped by clicking; Regarding the Labels are preprocessed; Calculate all preprocessed The attribute similarity between tags. Calculate all The similarity of text features between tags. Based on the attribute similarity and text feature similarity calculation The similarity between two labels; Based on the The similarity between two labels determines the similarity matrix; Cluster the label similarity matrix to obtain several The collection of tags is denoted as Cluster; From the several Get the Cluster where the target tag is located from the tag collection; Extract the URL based on the Cluster where the target tag is located.
4. The multi-platform directional data collection method according to claim 3, characterized in that: Calculate all preprocessed The attribute similarity between tags is calculated using the following formula: Among them, x and y represent the n-dimensional similarity vectors of two labels, ||x|| and ||y|| represent the L2 norm of x and y, respectively. i Represents the value of the i-th dimension of vector x, y i Represents the value of the i-th dimension of vector y. Calculate all The similarity of text features between tags is calculated using the following formula: Among them, x represents, y represents, Len(x text ) indicates that Len(y text ) means that Dep(x text ) means that Dep(y text )express.
5. The multi-platform directional data collection method according to claim 3, characterized in that: Based on the attribute similarity and text feature similarity calculation The similarity between two labels is calculated using the following formula: Similarity(x,y)=α×Similarity tfidf (x,y)+β×Similarity text (x,y) Among them, Similarity(x,y) represents the overall similarity of labels x and y. tfidf (x,y) represents the label attribute similarity of labels x and y. text (x,y) represents the text feature similarity of labels x and y, and α represents Similarity tfidf The weight coefficient of (x, y) is 0.4, and β represents Similarity text The weight coefficient of (x,y) is 0.
6.
6. The multi-platform directional data collection method according to claim 3, characterized in that: Extracting the URL of the page to be crawled and adding the extracted URL to the queue to be crawled specifically includes the following steps: WebDriver: load the configuration template, open the Chrome Webkit kernel, start the WebDriver engine, and set the initial URL of the webpage, the domain name allow_domain allowed to be crawled, and the domain name deny_domain denied to be crawled; the configuration template includes: template configuration module, collection rule module, exception handling module, error warning module, URL extraction module, page turning rule module, detailed information extraction module and anti-crawling module; Loading template rules: loading the configured template, which includes all modules except the anti-crawling module; Crawl the target website: start the crawler, start crawling according to the template loading rules, extract the URL of the detail page on the target website, and add it to the URL queue; Extracting details page data: taking out the URL from the URL queue according to the scheduling rules, accessing its corresponding details page, extracting details page data and saving it; Page turning: The crawling of the current page is completed. If there is a next page, continue to crawl the next page according to the page turning rule module, otherwise close the crawler. End: Crawler execution stops, log printing stops, and WebDriver is closed.
7. The multi-platform directional data collection method according to claim 6, characterized in that: Also include between step "WebDriver" and step "Add disguise information": Add camouflage information: load the anti-crawl module.
8. The multi-platform directional data collection method according to claim 1, characterized in that: The step of accessing the page corresponding to the URL and obtaining the HTML document of the page specifically includes the following steps: Configure master nodes and slave nodes: each web page is assigned a master node, and slave nodes are set according to the web page estimate; Redis initialization: According to the configured master node, a Redis message queue is allocated to each web page to store the URL extracted from the web page, ensuring that all slave nodes corresponding to the master node share the URL queue; Data crawling: including WebDriver initialization, loading configuration templates, URL extraction, and detail page data extraction; End: After the crawl is completed, save the Redis log, clear the cache, and close the master node and slave node.
9. The multi-platform directional data collection method according to claim 6, characterized in that: Processing and parsing the HTML document to obtain target data specifically includes the following steps: HTML document parsing: Get the Response object returned by the downloader, which includes the HTML file of the current page and the response status code; Determine whether the response code is 200. If it is not 200, it means the crawling has failed and the exception handling module is turned on. If it is 200, it means the crawling has succeeded. The HTML string is taken from the Response object and parsed based on BeautifulSoup to obtain the parsed data. Dom tree construction: After parsing with BeautifulSoup, the HTML string is obtained, and the carriage return, line feed, tab, special expressions and special characters are removed. The Dom tree is generated by parsing with HTMLResponse, and the element positioning method is adopted according to the page structure, and the methods of start_with() and contain() Response objects are used to locate the position of the field to be extracted; the element positioning method includes: id selector, class selector and tag selector; Data extraction: According to the location of the field to be extracted, based on the string() and extract_first() methods, extract the data corresponding to the field; Storage and downloading: The extracted fields are stored in the Items object and handed over to the pipeline, which triggers the pipeline method to store and download data.
10. A multi-platform directional data collection system, characterized in that: include: A target website determination module, used to determine the target website; A module for determining the position of the URL to be crawled on the page, used to determine the position of the URL to be crawled on the page in the target website; The URL extraction module of the page to be crawled is used to extract the URL of the page to be crawled and add the extracted URL to the queue to be crawled; The HTML document acquisition module of the page is used to access the page corresponding to the URL and obtain the HTML document of the page; The processing and parsing module is used to process and parse the HTML document to obtain target data.
