【问题标题】:Not getting json when using .text in bs4在bs4中使用.text时没有得到json
【发布时间】:2020-09-07 04:45:29
【问题描述】:

在这段代码中,我认为我犯了一个错误,因为当我打印它时我没有得到正确的json,实际上我什么也没得到,但是当我索引脚本时我得到了json,但使用@987654324 @ 什么都没有出现,我只想要 json

代码:

from bs4 import BeautifulSoup
from urllib.parse import quote_plus
import requests
import selenium.webdriver as webdriver

base_url = 'https://www.instagram.com/{}'

search = input('Enter the instagram account: ')

final_url = base_url.format(quote_plus(search))

response = requests.get(final_url)

print(response.status_code)
if response.ok:
    html = response.text
    bs_html = BeautifulSoup(html)
    scripts = bs_html.select('script[type="application/ld+json"]')
    print(scripts[0].text)

【问题讨论】:

  • 您使用了什么搜索字符串?我在repl code 中稍微调整了您的代码,但在输入"abcd" 时它可以工作。
  • 它没有提供脚本对吗?
  • 如果search = "abcd",它是一个公共页面。如果search="damodar.dahal" 是我的私人 Instagram 帐户,则它不起作用。
  • 我明白了,它在 python 中对我有用。你能查一下我的代码是否有错误,而不是修改后的错误

标签: python json web-scraping beautifulsoup


【解决方案1】:

print(scripts[0].text) 行更改为print(scripts[0].string)

scripts[0]是一个Beautiful SoupTag对象,其字符串内容可以通过.string属性访问。

来源:https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string

如果您想将字符串转换为 json 以便您可以访问数据,您可以执行以下操作:

...

if response.ok:
    html = response.text
    bs_html = BeautifulSoup(html)
    scripts = bs_html.select('script[type="application/ld+json"]')
    json_output = json.loads(scripts[0].string)

然后,例如,如果您运行print(json_output['name']),您应该能够访问帐户上的名称。

【讨论】:

  • 是的,它完成了这项工作,但是如果你知道的话,你能告诉我如何将它加载到 json 中吗?
  • 您是否尝试将其保存为 json 文件?
  • 相同的代码,但我正在尝试这个html = response.text bs_html = BeautifulSoup(html) scripts = bs_html.select('script[type="text/javascript"]') data = scripts[3].string jso = json.loads(data) print(jso)
  • 我正在尝试使用loads 并尝试将其打印出来,这样我就可以访问里面的数据了吗?
  • scripts[3] 不起作用,因为scripts 只有一个元素。查看编辑后的回复:)
猜你喜欢
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2022-10-25
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
相关资源
最近更新 更多