简体   繁体   English

缩进错误:使用 Selenium 和 Python 进行 web 抓取时出现意外缩进

[英]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 txt file?我想获取每个匹配项的 ID 号并将其保存在 txt 文件中?

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?任何人都可以帮我解决问题吗?

In python you must properly indent statements after ':'.在 python 中,您必须在“:”之后正确缩进语句。 Change改变

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

to

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

This error message...此错误消息...

IndentationError: unexpected indent

...implies that there were indentation errors in your code block. ...意味着您的代码块中存在缩进错误。


Python Indentation Python 压痕

Indentation refers to the spaces at the beginning of a code line. 缩进是指代码行开头的空格。 Python uses indentation to indicate a block of code. Python 使用缩进来表示代码块。


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 .充当代码块,将针对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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM