How to replace the Query field in the URL?

How to replace the Query field in the URL?

[[420519]]

When we write a crawler, we may need to generate a new URL based on the current URL in the crawler. For example, the following pseudo code:

  1. import re
  2. current_url = 'https://www.kingname.info/archives/page/2/'  
  3. current_page = re.search( '/(\d+)' , current_url). group (1)
  4. next_page = int (current_page) + 1
  5. next_url = re.sub( '\d+' , str(next_page), current_url)
  6. make_request(next_url)

The running effect is shown in the figure below:

But sometimes, the page turning parameter is not necessarily a number. For example, on some websites, visit a URL: https://xxx.com/articlelist?category=technology&after=asdrtJKSAZFD

When you access this URL, it returns a JSON string, and this JSON contains the following fields:

  1. ...
  2. "paging" : {
  3. "cursors" : {
  4. "before" : "MTA3NDU0NDExNDEzNTgz" ,
  5. "after" : "MTE4OTc5MjU0NDQ4NTkwMgZDZD"  
  6. },
  7.          
  8. }
  9. ...

This situation is more common in information flow websites. It can only scroll down infinitely to view the next page, and cannot jump directly by page number. The parameter after the next page is returned every time a request is made. When you want to access the next page, use this parameter to replace the parameter after after= in the current URL.

In this way, replacing the parameters in the URL is not a simple task. Because the URL may have 4 situations:

  • First page, no after parameter: https://xxx.com/articlelist?category=technology
  • The first page has the after parameter name but no value: https://xxx.com/articlelist?category=technology&after=
  • On subsequent pages, there is no content after the after parameter value: https://xxx.com/articlelist?category=technology&after=asdrtJKSAZFD
  • On the subsequent pages, there is content after the aster parameter value: https://xxx.com/articlelist?category=technology&after=asdrtJKSAZFD&other=abc

You can try to cover these 4 situations and generate the URL of the next page using regular expressions.

In fact, we don't need to use regular expressions. Python's built-in urllib module already provides a solution to this problem. Let's take a look at a piece of code:

  1. from urllib.parse import urlparse, urlunparse, parse_qs, urlencode
  2.  
  3.  
  4. def replace_field(url, name , value):
  5. parse = urlparse(url)
  6. query = parse.query
  7. query_pair = parse_qs(query)
  8. query_pair[ name ] = value
  9. new_query = urlencode(query_pair, doseq= True )
  10. new_parse = parse._replace(query=new_query)
  11. next_page = urlunparse(new_parse)
  12. return next_page
  13.  
  14. url_list = [
  15. 'https://xxx.com/articlelist?category=technology' ,
  16. 'https://xxx.com/articlelist?category=technology&after=' ,
  17. 'https://xxx.com/articlelist?category=technology&after=asdrtJKSAZFD' ,
  18. 'https://xxx.com/articlelist?category=technology&after=asdrtJKSAZFD&other=abc'  
  19. ]
  20.  
  21. for url in url_list:
  22. next_page = replace_field(url, 'after' , '0000000' )
  23. print(next_page)

The running effect is shown in the figure below:

As can be seen from the figure, in these four cases, we can successfully add the parameter after = 0000000 for the next page. There is no need to consider how regular expressions can adapt to all situations.

Among them, urlparse and urlunparse are a pair of opposite functions. The former converts the URL into a ParseResult object, and the latter converts the ParseResult object back to a URL string.

The .query property of the ParseResult object is a string, which is the content after the question mark in the URL, in the following format:

parse_qs and urlencode are also a pair of opposite functions. The former converts the string output by .query into a dictionary, while the latter converts the field into a string in the form of .query:

After using parse_qs to convert the query into a dictionary, you can modify the parameter value and then convert it back again.

Since the .query property of the ParseResult object is a read-only property and cannot be overwritten, we need to call an internal method ._replace to replace the new .query field and generate a new ParseResult object. Finally, convert it back to a URL.

The above is what we introduced today, how to use the functions that come with urllib to replace the fields in the URL.

<<:  GSMA: 5G networks will cover two-fifths of the world's population by 2025

>>:  5G in numbers: 5G trends revealed by statistics in the first half of 2021

Recommend

Which industry will be the hot spot for artificial intelligence in the 5G era?

In this process, many applications are constantly...

CloudCone: $16.5/year-dual-core/1GB/50GB/3TB@1Gbps/Los Angeles data center

CloudCone's Christmas Sale has begun. The mer...

If 12345G were in a WeChat group, what would they talk about?

[[269676]] Scene 1 The development and rise and f...

2017 Prediction: Will Networking and Security Finally Merge?

[51CTO.com Quick Translation] It’s a new year aga...

It’s time to show the real technology! See 5G+IoT=?

The Internet of Things is already booming, and it...

Guava RateLimiter: A practical guide to efficient flow control

background With the rapid development of the Inte...

This article teaches you to understand the TCP/IP protocol

It's the golden March and April again, and I&...

A brief introduction to spatial transformer networks

The first model I got to implement as part of my ...

What is WebDAV protocol? Do you know?

This article will introduce the basic concepts, a...

5G speed is already incredible, is 6G network coming?

Now 4G network signals have been popularized all ...