[英]Python and using lxml to find part if a string using lxml html
我有一個看起來像這樣的標簽...
<div id="contentDiv_reviewHistoPop_B004HYGU18_4792" style="display:none;">
我可以用
doc = lxml.html.document_fromstring(html)
el = doc.get_element_by_id('contentDiv_reviewHistoPop_B004HYGU18_4792')
查找標簽,但是如何使用例如通配符查找contentDiv_reviewHistoPop *來查找包含字符串一部分的標簽?
謝謝
你應該做這個...
import lxml.etree as ET
from lxml.etree import XMLParser
parser = XMLParser(ns_clean=True, recover=True)
html = """<html><body><div id="contentDiv_reviewHistoPop_B004HYGU18_4792" style="display:none;"></body></html>"""
tree = ET.fromstring(html, parser)
tmp = list()
for elem in tree.iter():
if elem.tag == 'div':
for ii in elem.items():
if (ii[0].lower() == 'id') and ('contentDiv_reviewHistoPop' in ii[1]):
tmp.append(elem)
tmp
將包含具有匹配文本的匹配div元素列表。
如果只能使用lxml.html
,請執行此操作...
import lxml.html
html = """<html><body><div id="contentDiv_reviewHistoPop_B004HYGU18_4792" style="display:none;"></body></html>"""
doc = lxml.html.document_fromstring(html)
tmp = list()
for elem in doc.iter():
if elem.tag == 'div':
for ii in elem.items():
if (ii[0].lower() == 'id') and ('contentDiv_reviewHistoPop' in ii[1]):
tmp.append(elem)
再次... tmp將包含匹配的標簽
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.