Code work in IDLE but not in PyCharm

Question:

The code worked in IDLE, but not in Pycharm, this is the complete code:

import sys
import urllib
import urllib2
from bs4 import BeautifulSoup
type_keyword = "唯品会与消协共同搭建绿色维权通道"
url = "http://www.baidu.com/s?wd=" +      urllib.quote(type_keyword.decode(sys.stdin.encoding).encode('gbk'))
openpage = urllib2.urlopen(url).read()
soup = BeautifulSoup(openpage)
for child in soup.findAll("h3", {"class": "t"}):
    geturls = child.a.get('href')
    print urllib2.urlopen(geturls).geturl()

After I clicked “run” Pycharm will return error as follows:

C:Python27python.exe C:/Python27/ParseWeb/ParseWeb.py
File "C:/Python27/ParseWeb/ParseWeb.py", line 3
SyntaxError: Non-ASCII character 'xe4' in file     C:/Python27/ParseWeb/ParseWeb.py on line 3, but no encoding declared; see   http://python.org/dev/peps/pep-0263/ for details
Process finished with exit code 1

It’s quite interesting that no matter what I put in line 3, Pycharm will give the error result..

What could be the cause? Thanks!

Asked By: RachaelT

||

Answers:

Try adding the following line at the start of the file.

# -*- coding: utf-8 -*-

You can read more about this for example here

Answered By: Shridhar R Kulkarni

The code you pasted does not have any such character as the error indicates on line 3.

If C:/Python27/ParseWeb/ParseWeb.py is not the name of the file you want to run, you can try having the file you want to run open in PyCharm, and press Ctrl+Shift+F10 (which runs the currently open file).

You should also define the encoding of your Python files by adding this within the first two lines of the file:

# -*- coding: utf-8 -*-

This seems to be necessary as well as you have non-ASCII characters in the code, but the first thing to ensure is that you are running the correct file.

Answered By: user7706437
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.