# kivy 沒支援目前版本(4.9.2)的 lxml 的 alternative 方案 =》beautifulSoup, xml2dict, pyquery ... --- 需求: [kivy 使用 kivy ,Camera + autopredictor 拍照後傳回辨識檔案,使用 python kivy套件寫 iOS 和 Android APP](https://hackmd.io/@cssmiley/rk3T64_l3) lxml 模組錯誤暫時無解,安裝到模擬器跑一直報錯只好改用bs4模組完成一樣的作用 lxml 原本的作用 ``` # 解析 response HTML 取得 _token, cookies from lxml import html tree = html.fromstring(response.text) _token =tree.xpath('//input[@name="_token"]/@value') ``` 錯誤: dynamic module does not define module export function (PyInit_etree) [lxml alternatives and similar packages](https://python.libhunt.com/lxml-alternatives) 解決: 參考下面的方式改成使用 BeautifulSoup 解析 - [can we use XPath with BeautifulSoup?](https://stackoverflow.com/questions/11465555/can-we-use-xpath-with-beautifulsoup) BeautifulSoup has a function named findNext from current element directed childern,so: ``` father.findNext('div',{'class':'class_value'}).findNext('div',{'id':'id_value'}).findAll('a') ``` Above code can imitate the following xpath: ``` div[class=class_value]/div[id=id_value] ``` - [lxml.html](https://lxml.de/lxmlhtml.html) - [xpath即時轉換](http://xpather.com) - 重要[【Day 09】- 大家都愛的 BeautifulSoup](https://ithelp.ithome.com.tw/articles/10271319?sc=iThelpR) -重要 [什麼是XPath](https://matthung0807.blogspot.com/2017/12/xpath.html) - [CSS2XPath](https://css2xpath.github.io) - 重要[安装解析器 html.parser](https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id13) - 將原本 lxml 的 code 修改成使用 BeautifulSoup的方式: ``` # 暫時先使用mock data 和 BeautifulSoup代替上面的lxml soup = BeautifulSoup(html_doc, 'html.parser') # 使用內建的 html.parser 解析,不用另外裝 html5lib #soup = BeautifulSoup(html_doc, 'html5lib') print(soup.prettify()) _token = soup.input.findNext("input",{"name":"_token"})["value"] ```