如何获取文本<script>



前段时间我用下面的代码来获取window._sharedData;但是刚才同样的代码没有办法,我该怎么办

如果我将script更改为div它可以工作,但我需要使用script

code.py

from bs4 import BeautifulSoup
html1 = '<h1><script>window._sharedData;</script></h1>'
soup = BeautifulSoup(html1)
print(soup.find('script').text)

添加html.parserlxml并调用.string而不是.text

from bs4 import BeautifulSoup
html = '<h1><script>window._sharedData;</script></h1>'
soup = BeautifulSoup(html, 'html.parser')
print(soup.find('script').string)

你应该使用BeautifulSoup(html1, 'lxml')而不是BeautifulSoup(html1)。如果输出为空,则将使用.string而不是.text。你可以试试:

from bs4 import BeautifulSoup
html1 = '<h1><script>window._sharedData;</script></h1>'
soup = BeautifulSoup(html1, 'lxml')
print(soup.find('script').text)

print(soup.find('script').string)

输出将是:

window._sharedData;