在Python中的脚本标签中进行Web爬取

问题描述

我设法使用BeautifulSoup获取了脚本标签。然后我变成了json对象。我想要的信息在data['x']内,但卡在b标签之间。 例子:

<b>infoiwant</b><br>NA<br>infoinwant</br>columniwant: 123','<b>infoiwant</b><br>NA<br>columniwant: 123'</br>columniwant: 123

我将如何从这两个b元素中获取信息

解决方法

在转换为json之前,可以使用BeautifulSoup get_text()方法吗?也许像

soup.find('b').get_text()
,

一种使用<script>模块从re标记中提取数据的方法:

import re
from bs4 import BeautifulSoup


html_text = """
<script>
var data['x'] = '<b>infoiwant</b><br>NA<br>infoinwant</br>columniwant: 123';
</script>
"""

html_data = re.search(r"data\['x'\] = '(.*?)';",html_text).group(1)
soup = BeautifulSoup(html_data,"html.parser")

print(soup.find("b").get_text(strip=True))

打印:

infoiwant

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...