最近用python的lxml庫解析了個html文件,在windows python3.8下面運行沒什么問題,但是在centOS python2.7環境下一直報錯 ImportError: cannot import name etree
網上有人說lxml版本不一樣,有的沒帶etree模塊,所以我准備安成3.7.1版本的,結果安裝報錯了
building 'lxml.etree' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src creating build/temp.linux-x86_64-2.7/src/lxml gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Isrc/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -w unable to execute gcc: No such file or directory Compile failed: command 'gcc' failed with exit status 1 creating tmp cc -I/usr/include/libxml2 -c /tmp/xmlXPathInitNChIqO.c -o tmp/xmlXPathInitNChIqO.o unable to execute cc: No such file or directory ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* error: command 'gcc' failed with exit status 1 ---------------------------------------- Rolling back uninstall of lxml
安裝gcc編譯器
yum install -y gcc
還是報錯
src/lxml/lxml.etree.c:82:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilation terminated. Compile failed: command 'gcc' failed with exit status 1 creating tmp cc -I/usr/include/libxml2 -c /tmp/xmlXPathInitH1t6CR.c -o tmp/xmlXPathInitH1t6CR.o /tmp/xmlXPathInitH1t6CR.c:1:26: fatal error: libxml/xpath.h: No such file or directory #include "libxml/xpath.h" ^ compilation terminated. ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* error: command 'gcc' failed with exit status 1 ---------------------------------------- Rolling back uninstall of lxml
安裝python dev
yum install python-devel
這里要用devel 不然也會報錯
叒報錯
/tmp/xmlXPathInitK4VuBC.c:1:26: fatal error: libxml/xpath.h: No such file or directory
接着安
yum install libxml2-devel libxslt-devel
終於安上了!
但是運行仍舊報錯。。
因為lxml是第三方的庫,所以在Linux下面運行會有點問題。
后面我依次試了手動安裝、搭建環境、修改系統變量等等一系列操作,都仍然報這個錯,人都要裂開了
后來經同事提醒才發現,是我的文件命名有問題!因為io是其中的模塊,所以識別錯誤。
把文件名稱改了就好了!比如改成ioio.py。。
雖然搜的時候看到了有人說命名成了關鍵字:https://blog.csdn.net/Amberdreams/article/details/80548742
但他用的關鍵字是lxml,我沒想到io也是關鍵字,以后所有的python文件命名我必須多加幾個下划線,浪費我一上午加一中午,靠!
但是中間的搭建環境、手動安裝等操作我不知道到底有沒有用,但我覺得手動安裝和搭建環境應該還是有用的,因為沒設置的時候我直接在命令行輸入from lxml import etree 都不行,之后可以了,但是文件運行不了。
官方地址:https://lxml.de/2.1/build.html
主要就是下載並解壓tar.gz文件然后在解壓的lxml目錄運行:
python setup.py build_ext -i