使用Python从Java脚本提取文本 [英] Extract Text from Javascript using Python
问题描述
我一直在研究如何执行此操作的示例,但还不太清楚.我正在使用beautifulsoup抓取一些数据-可以使用它来查找所需的数据,但是它包含在以下代码块中.我正在尝试从中提取时间戳信息.我有一个正则表达式在这里起作用的感觉,但我似乎无法弄清楚-有什么建议吗?
I've been looking at examples of how to do this but can't quite figure it out. I'm using beautifulsoup to scrape some data - I am able to use it to find the data I want, but it is contained in the following block of code. I'm trying to extract the timestamp information from it. I have a feeling regular expressions work here but I can't seem to figure it out - any suggestions??
<script class="code" type="text/javascript">
$(document).ready(function(){
line1 = [['2009-02-23 10 AM', 5203], ['2009-02-08 10 AM', 3898], ['2009-02-09 10 AM', 4923], ['2009-02-22 10 AM', 3682], ['2009-02-21 10 AM', 3238], ['2009-02-20 10 AM', 4648]];
options1 = {
etc other text
}
});
</script>
推荐答案
您不能使用BS来获取此数据-BS仅适用于HTML/XML,而不适用于JavaScript.
You can't use BS to get this data - BS works only with HTML/XML, not JavaScript.
您必须使用regular expressions
或标准字符串函数.
You have to use regular expressions
or standart string functions.
text = '''<script class="code" type="text/javascript">
$(document).ready(function(){
line1 = [['2009-02-23 10 AM', 5203], ['2009-02-08 10 AM', 3898], ['2009-02-09 10 AM', 4923], ['2009-02-22 10 AM', 3682], ['2009-02-21 10 AM', 3238], ['2009-02-20 10 AM', 4648]];
options1 = {
etc other text
}
});
</script>'''
import re
re.findall("'([^']*)'", text)
结果:
['2009-02-23 10 AM',
'2009-02-08 10 AM',
'2009-02-09 10 AM',
'2009-02-22 10 AM',
'2009-02-21 10 AM',
'2009-02-20 10 AM']
这篇关于使用Python从Java脚本提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!