我正在尝试提取类名称的内容。如何提取所有内容,包括'em'标签内以及'em'标签后的内容?参见下图:
审判1:
driver = webdriver.Chrome(options=options)
sel = Selector(text = driver.page_source)
sel.xpath("//*[@class ='st']").extract()
输出1:
>> <span class="st"><span class="f">Nov 26, 2018 - </span>First #<em>GDPR fine</em> awarded in Germany. 330,000 user data stolen. Usernames and passwords stored in plaintext. €20,000 <em>fine</em>. Why "so low"?</span>
审判2:
driver = webdriver.Chrome(options=options)
sel = Selector(text = driver.page_source)
sel.xpath("//*[@class ='st']/text()").extract()
输出2:
>> First #
理想情况下,我想要获得的输出是:
>> Nov 26, 2018 - First #GDPR fine awarded in Germany. 330,000 user data stolen. Usernames and passwords stored in plaintext. €20,000 fine. Why "so low"?
答案 0 :(得分:0)
我最终找到了一种解决问题的方法,尽管它不是一种优雅的方法,但仍然欢迎一种更为优雅的解决方案。
我使用以下方法提取了类名的内容:
driver = webdriver.Chrome(options=options)
sel = Selector(text = driver.page_source)
content = sel.xpath("//*[@class ='st']").extract()
然后我定义了一个将html从文本中剥离的函数:
import html.parser
class HTMLTextExtractor(html.parser.HTMLParser):
def __init__(self):
super(HTMLTextExtractor, self).__init__()
self.result = [ ]
def handle_data(self, d):
self.result.append(d)
def get_text(self):
return ''.join(self.result)
def html_to_text(html):
s = HTMLTextExtractor()
s.feed(html)
return s.get_text()
遍历列表中的内容并一次剥离html,这给了我想要的结果:
m = []
for w in content:
z = html_to_text(w)
m.append(z)