【问题标题】:Json , scrape into web page - pythonJson,抓取到网页 - python
【发布时间】:2018-12-13 04:35:42
【问题描述】:

我正在使用 Python 中的 requests 和 beautifulsoup 库抓取某些网页

所以我在这个简单的代码中得到了我想要的元素

<script>
data = {'user':{'id':1,'name':'joe','age':18,'email':'joe@hotmail.com'}}
</script>

所以我想在变量中获取电子邮件值 但是整个元素又回到列表中,当我指定该标签的文本时 我无法将它放入 json 它给我列中的错误 所以有什么想法吗? 我会很感激任何帮助

【问题讨论】:

    标签: python json dictionary web-scraping


    【解决方案1】:

    一些简单的东西,也许会对你有所帮助。

    import json
    from bs4 import BeautifulSoup
    
    html = """
    <script>
    data = {'user':{'id':1,'name':'joe','age':18,'email':'joe@hotmail.com'}}
    </script>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    # slices [7:] mean that we ignore the `data = `
    # and replace the single quotes to double quotes for json.loads()
    json_data = json.loads(soup.find('script').text.strip()[7:].replace("'", '"'))
    print(json_data)
    print(type(json_data))
    

    输出

    {'user': {'id': 1, 'name': 'joe', 'age': 18, 'email': 'joe@hotmail.com'}}
    <class 'dict'>
    

    【讨论】:

    • 你离我想要的已经足够近了,我也这样做了,并在列 code json_data = json.loads(soup.find_all('script')[3].text .strip()[21:]) 文件“C:\Users\TOSHIBA\AppData\Local\Programs\Python\Python36-32\lib\json_init_.py”,第 354 行,加载中返回 _default_decoder.decode(s) 文件“C:\Users\TOSHIBA\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py”,第 342 行,在 decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 3548 (char 3547)
    • 你能显示你要抓取的script标签吗?
    • 我不确定我是否可以在这里做,因为它太长了
    • 这可能对你有帮助,我想你有很多 dict 对象,stackoverflow.com/questions/21058935/…
    • 这可能是因为末尾的;。使用 [7:-1] 之类的东西,而不是 [7:]。此外,比使用此类幻数更可靠的是获取脚本标记内容中第一个 { 和最后一个 } 之间的所有内容并将其解析为 JSON。
    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 2022-01-27
    • 1970-01-01
    相关资源
    最近更新 更多