Search code examples
pythonpython-3.xseleniumweb-scrapingindentation

IndentationError: unexpected indent while web scraping using Selenium and Python


I want to get the id number of the each match and save it in a text file?

from selenium import webdriver
from bs4 import BeautifulSoup

url = "http://vip.win007.com/history/Odds_big.aspx?date=2020-8-1"
driver = webdriver.Chrome()
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')

container0 = soup.find_all("odds", {"match": "id"})
print container0

with open('c:/logs/kellyrate.txt','a') as kellyrate:
kellyrate.write(container0 + "\n")

After run the script:

>>>IndentationError: unexpected indent

Anyone can help me to solve the problem?


Solution

  • This error message...

    IndentationError: unexpected indent
    

    ...implies that there were indentation errors in your code block.


    Python Indentation

    Indentation refers to the spaces at the beginning of a code line. Python uses indentation to indicate a block of code.


    This usecase

    In your program, the line of code:

    kellyrate.write(container0 + "\n")
    

    acts as a block of code which will be iterated for each line in c:/logs/kellyrate.txt. So you need to indent this line of code either by:

    • tab character
    • blank space characters

    So your effective code block will be:

    with open('c:/logs/kellyrate.txt','a') as kellyrate:
        kellyrate.write(container0 + "\n")