设置向上
我有各种包含HTML的字符串变量,其中一个https://pastebin.com/rsi3v9nh。
我需要获取HTML中的文本。例如。来自以下HTML代码段,
<div class="woocommerce-product-details__short-description">\n<ul>\n<li>50.000 r.p.m.</li>\n<li>Dry technique</li>\n<li>Controllable by foot pedal</li>\n<li>Auto-Cruise</li>\n<li>Twist-lock system</li>\n<li>100W drill power</li>\n<li>7.8 Ncm torque</li>\n<li>220V-240V</li>\n<li>12-months warranty</li>\n</ul>\n</div>\n<p>[/vc_column_text]</p>
我想获取所有<li>
的文字。
请注意,这只是整个字符串的一部分示例,文本不仅在<li>
个元素中。
问题
简单地使用正则表达式会非常麻烦,因为模式有点不规则。
我熟悉Selenium从HTML获取数据,即做driver.find_element_by_xpath('div')
等。但这只适用于HTML对象,而不是字符串。
我想知道我是否能以某种方式将字符串转换为HTML,然后以类似Selenium的方式获取文本。
任何其他解决方案也可以。
答案 0 :(得分:2)
You definitely don't want to use regular expressions here.
您可以使用beautifulsoup
来解析它:
from bs4 import BeautifulSoup
s = '<div class="woocommerce-product-details__short-description">\n<ul>\n<li>50.000 r.p.m.</li>\n<li>Dry technique</li>\n<li>Controllable by foot pedal</li>\n<li>Auto-Cruise</li>\n<li>Twist-lock system</li>\n<li>100W drill power</li>\n<li>7.8 Ncm torque</li>\n<li>220V-240V</li>\n<li>12-months warranty</li>\n</ul>\n</div>\n<p>[/vc_column_text]</p>'
soup = BeautifulSoup(s)
print(soup.findAll(text=True))
输出:
['\n', '\n', '50.000 r.p.m.', '\n', 'Dry technique', '\n', 'Controllable by foot pedal', '\n', 'Auto-Cruise', '\n', 'Twist-lock system', '\n', '100W drill power', '\n', '7.8 Ncm torque', '\n', '220V-240V', '\n', '12-months warranty', '\n', '\n', '\n', '[/vc_column_text]']