IndexError: List index out of range in Python

Dung Do Tien Jan 22 2021 104

I'm running my code in Python Ver3.9(Window10) and get the error status: list index out of range, I want to crawl the data snippet in image(District / County</th><td>) as text by code, here my code and the image I want crawl:

IndexError: List index out of range in Python

 #!/usr/bin/python
import requests

IP  = "8.8.8.8"
def District(IP):
    try:
        URL = "https://db-ip.com/"
        IP_TARGET = URL + IP
        response1 = requests.get(IP_TARGET)
        data_district = str(response1.content)
        data_district = data_district.split("County</th><td>   ")
        data_district = data_district[1].split("</td></tr>")
        print("[+] District/County: " + data_district[0])
    except IndexError as e:
        print("[+] District/County: Not Found", e)
District(IP)

In my program, I have a html to crawl, I need a solution to solve it thoroughly on my computer and others too. Help me, many tks guys! 

Have 1 answer(s) found.
  • B

    Blue Jame Jan 21 2021

    Okay, here my solutions :

    Step 1: redefine the code that contains the characters you need to get.

    Step 2: "Santa Clara" are the characters you need to get.

    Step 3: Filter unnecessary characters to get the text "Santa Clara", (you made a mistake in this step).

    - You re' wrong in that data_district.split ("County </th> <td>n ")

    - It's must be data_district.split ("County </th> <td>\\n ")

    Explain: In python blank characters are replaced with the character "\\ n", so that Here is the complete code you need:

      #!/usr/bin/python
    import requests
    
    IP  = "8.8.8.8"
    def District(IP):
        try:
            URL = "https://db-ip.com/"
            IP_TARGET = URL + IP
            response1 = requests.get(IP_TARGET)
            data_district = str(response1.content)
            data_district = data_district.split("County</th><td>\\n")
            data_district = data_district[1].split("</td></tr>")
            print("[+] District/County: " + data_district[0])
        except IndexError as e:
            print("[+] District/County: Not Found", e)
    District(IP) 

    I hope my solution useful for you, If you still have questions, please comment below for my support:)))

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close