Skip to main content
 首页 » 编程设计

python之如何从html表格行中提取文本

2024年09月07日8birdshome

这是我的字符串:

content = '<tr class="cart-subtotal"><th>RTO / Registration office :</th><td><span class="amount"><h5>Yadgiri</h5></span></td></tr>' 

我已经尝试使用正则表达式来提取 h5 元素标签之间的文本:

   reg = re.search(r'<tr class="cart-subtotal"><th>RTO / Registration office :</th><td><span class="amount"><h5>([A-Za-z0-9%s]+)</h5></span></td></tr>' % string.punctuation,content) 

返回的正是我想要的。

有没有更多的 pythonic 方法来获得这个?

请您参考如下方法:

不知道这是否符合更多 pythonic 的条件,但它将它作为 HTML 数据处理。

from lxml import html 
content = '<tr class="cart-subtotal"><th>RTO / Registration office :</th><td><span class="amount"><h5>Yadgiri</h5></span></td></tr>' 
HtmlData = html.fromstring(content) 
ListData = HtmlData.xpath(‘//text()’) 

获取最后一个元素:

ListData[-1]