【问题标题】:Web Scraping in a script tag in PythonPython中脚本标签中的Web抓取
【发布时间】:2020-12-29 10:03:54
【问题描述】:

我已经设法使用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 元素中获取信息

【问题讨论】:

  • .find_all('b') 应该足以获取 b 标签。 br 给其他人。

标签: python json selenium web-scraping beautifulsoup


【解决方案1】:

在转成json之前,能不能用BeautifulSoup的get_text()方法?也许像

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

【讨论】:

  • 和 来自 html 中的脚本标记。所以使用 find b 方法对我不起作用
【解决方案2】:

&lt;script&gt;标签中提取数据的一种方法是使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2017-05-21
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多